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

前端 未结 5 1605
囚心锁ツ
囚心锁ツ 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:39

    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'
    

提交回复
热议问题