How to split a string in Python?

后端 未结 2 1951
借酒劲吻你
借酒劲吻你 2021-01-03 00:39

I have read the documentation but don\'t fully understand how to do it.

I understand that I need to have some kind of identifier in the string so that the functions

2条回答
  •  失恋的感觉
    2021-01-03 01:38

    Use the split method on strings:

    >>> "Sico87 is an awful python developer".split(' ', 1)
    ['Sico87', 'is an awful python developer']
    

    How it works:

    1. Every string is an object. String objects have certain methods defined on them, such as split in this case. You call them using obj.().
    2. The first argument to split is the character that separates the individual substrings. In this case that is a space, ' '.
    3. The second argument is the number of times the split should be performed. In your case that is 1. Leaving out this second argument applies the split as often as possible:

      >>> "Sico87 is an awful python developer".split(' ')
      ['Sico87', 'is', 'an', 'awful', 'python', 'developer']
      

    Of course you can also store the substrings in separate variables instead of a list:

    >>> a, b = "Sico87 is an awful python developer".split(' ', 1)
    >>> a
    'Sico87'
    >>> b
    'is an awful python developer'
    

    But do note that this will cause trouble if certain inputs do not contain spaces:

    >>> a, b = "string_without_spaces".split(' ', 1)
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: need more than 1 value to unpack
    

提交回复
热议问题