Remove the first word in a Python string?

后端 未结 4 1765

What\'s the quickest/cleanest way to remove the first word of a string? I know I can use split and then iterate on the array to get my string. But I\'m pretty s

4条回答
  •  不思量自难忘°
    2020-12-25 11:08

    The other answer will raise an exception if your string only has one word, which I presume is not what you want.

    One way to do this instead is to use the str.partition function.

    >>> s = "foo bar baz"
    >>> first, _, rest = s.partition(" ")
    >>> rest or first
    'bar baz'
    
    >>> s = "foo"
    >>> first, _, rest = s.partition(" ")
    >>> rest or first
    'foo'
    

提交回复
热议问题