BernardL BernardL - 1 year ago 76
Python Question

Return substring if contains character

Given a string, "Bajsd 2-478 1278123" and string similar to that. Is there a method to pull only the substring which contains "-"?

So in this case, it would be, 2-478. The length of the entire string and the substring containing "-" can vary.

Answer Source

Just split the string and print the item if it contains "-"

print "".join([x for x in "Bajsd 2-478 1278123".split(" ") if "-" in x])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download