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

前端 未结 5 1603
囚心锁ツ
囚心锁ツ 2020-11-30 20:45

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 = \"Userna         


        
5条回答
  •  春和景丽
    2020-11-30 21:31

    You don't need regex for this

    >>> s = "Username: How are you today?"
    

    You can use the split method to split the string on the ':' character

    >>> s.split(':')
    ['Username', ' How are you today?']
    

    And slice out element [0] to get the first part of the string

    >>> s.split(':')[0]
    'Username'
    

提交回复
热议问题