What's the most Pythonic way to find the first of multiple single character substrings (if any) in a string?
To be clear, a string can contain multiple characters of interest and I want to find the first one - any one, I don't care which & don't need to know which. I just want to know that one of those characters occurred and the first point in the string where any of them occurred (thus, clearly not a dupe of the suggested question).
endDigitPos = digitText.find(['u', ' ', ')', '}', '/*'])
Isn't doing it
I am generically parsing C code - any C code. I am actually looking for hex strings, which start with 0x; having found that, I want to find the end of the hex string, which will be a space a close bracket, a space, a u if it is unsigned, or the end of line.
digitText starts 0x and ends with one of those chars.
The code above gives
endDigitPos = digitText.find(['u', ' ', ')', '}', '/*'])
TypeError: must be str, not list
I don't think there's anything that does this out of the box, but it's pretty easy to implement as regex
import re
def find_many(instring, *substrings):
pat = re.compile('|'.join([re.escape(s) for s in substrings]))
match = pat.search(instring)
if match is None:
return -1
else:
return match.start()
substrings = ['u', ' ', ')', '}', '/*']
find_many('aaa/*', *substrings) # 3
find_many('aaab', *substrings) # -1
find_many('uaaa/*', *substrings) # 0
No idea of whether this is "the most pythonic" way, but one option would be
index = next(i for i,c in enumerate(s) if c in {'u', ' ', ')', '}', '/'})
Note: This will raise a StopIteration in case no item is found. Adapt as needed depending on what you would like to have as the "item is not there" case.
Note2: As Patrick pointed out in the comments, this only works for single-characters, so if you need the multi-substring approach go for his proposed solution
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With