I want to be able to check what the first substring in the string: random_string = "fox is bright orange" is without needing to split the string and then read from the list, or store it some other variable. Is it possible to do this?
the string I am using here is just an example, so there is not a designated string being used. I want to be able to figure out the substring (if it were split by ' ') of any string without having to use a list
So you want to get fox from fox is bright orange:
Regex; ^\w+ gets one or more alphanumerics from start:
In [61]: re.search(r'^\w+', random_string).group()
Out[61]: 'fox'
str.partition (which produces a tuple) and getting the first element
In [62]: random_string.partition(' ')[0]
Out[62]: 'fox'
Do you want to check whether a given string begins with a certain word?
random_string = "fox is bright orange"
print(random_string.startswith("fox ") # True
Do you want to get the length of the first word?
random_string = "fox is bright orange"
print(random_string.index(" ")) # 3
Do you want to get the first word, but not split anything else?
random_string = "fox is bright orange"
print(random_string[:random_string.index(" ")]) # fox
Note that str.index() raises ValueError when the specified substring isn't found, i.e. when there's only one word in the string, so if you use one of the last two solutions, you should catch that error and do something appropriate (such as using the whole string).
random_string = "fox is bright orange"
try:
print(random_string[:random_string.index(" ")])
except ValueError:
print(random_string)
Or you could use str.find() instead. This returns -1 when the substring isn't found, which you would have to handle a little differently.
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