Reputation: 5464
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.
Upvotes: 0
Views: 57
Reputation: 5391
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])
Upvotes: 3
Reputation: 2242
With regular expressions:
import re
re.search("(\d-\d+)", "Bajsd 2-478 1278123").group()
Upvotes: 1
Reputation: 16740
Just use the split
method along with testing if a substring contains "-":
>>> s = "Bajsd 2-478 1278123"
>>> splitted = s.split(" ")
>>> [substring for substring in splitted if "-" in substring][0]
"2-478"
The line [substring for substring in splitted if "-" in substring][0]
means: "make a list out of the elements of splitted
that contain "-"
, and return the head of this list".
Upvotes: 0