How would I get everything before a : in a string Python
Just use the split
function. It returns a list, so you can keep the first element:
>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'
Using index
:
>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'
The index will give you the position of :
in string, then you can slice it.
If you want to use regex:
>>> import re
>>> re.match("(.*?):",string).group()
'Username'
match
matches from the start of the string.
you can also use itertools.takewhile
>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'