Split a string in python into only two parts starting from the left

14,435

Solution 1

split can take a second parameter that defines how many splits you would like to do. If you only want two elements, you can just split once.

>>> s = 'acquire Wooden Shield'
>>> s.split(' ', 1)
['acquire', 'Wooden Shield']

str.split([sep[, maxsplit]]) If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

Solution 2

string.split(' ', 1)

Second parameter is the number of matches

Reference here

Share:
14,435
Admin
Author by

Admin

Updated on June 24, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a string from input() that I would like to only split into two parts with the delimiter as a space, even though a space may occur more than twice.

    For instance, if the input string was

    'acquire Wooden Shield'
    

    the resulting list I want would be

    ['acquire', 'Wooden Shield]
    

    I would assume this is pretty simple to do, thanks.