How to split a sentence into two parts in python? If there is the following,
for example:
# input:
'To Kill a Mockingbird by Harper Lee'
# output:
['To Kill a Mockingbird' 'Harper Lee']
How to split a sentence into two parts in python? If there is the following,
for example:
# input:
'To Kill a Mockingbird by Harper Lee'
# output:
['To Kill a Mockingbird' 'Harper Lee']
You can use split
string = 'To Kill a Mockingbird by Harper Lee'
string_list = string.split(" by ")
#output
['To Kill a Mockingbird', 'Harper Lee']
i did " by "
instead of "by"
because other wise you get spaces at the end and start
['To Kill a Mockingbird ', ' Harper Lee']
Using str.split()
is the right tool for the job:
Return a list of the words in the string, using sep as the delimiter string. 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).
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].
You have written that you want exactly two parts from the sentence. So you have to use the second argument of the str.split(sep, maxsplit)
method, too. That ensures you to split a given string by a separator only n times:
'To Kill a Mockingbird by Harper Lee by foo'.split(" by ") # gives you 3 parts
['To Kill a Mockingbird', 'Harper Lee', 'foo']
'To Kill a Mockingbird by Harper Lee by foo'.split(" by ", 1) # gives you exactly 2 parts
['To Kill a Mockingbird', 'Harper Lee by foo']
This is the case for only one separator (and your test sentence), too, of course:
'To Kill a Mockingbird by Harper Lee'.split(" by ", 1)
['To Kill a Mockingbird', 'Harper Lee']
Also nice to know is that there is also str.rsplit()
doing similar things:
If maxsplit is given, at most maxsplit splits are done, the rightmost ones.