BernardL
BernardL

Reputation: 5464

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.

Upvotes: 0

Views: 57

Answers (3)

Daniel
Daniel

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

Brian
Brian

Reputation: 2242

With regular expressions:

import re
re.search("(\d-\d+)", "Bajsd 2-478 1278123").group()

Upvotes: 1

Right leg
Right leg

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

Related Questions