How would I get everything before a : in a string Python

0Cool picture 0Cool · Dec 9, 2014 · Viewed 203.3k times · Source

I am looking for a way to get all of the letters in a string before a : but I have no idea on where to start. Would I use regex? If so how?

string = "Username: How are you today?"

Can someone show me a example on what I could do?

Answer

fredtantini picture fredtantini · Dec 9, 2014

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'