Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into two parts only [duplicate]

Tags:

python

split

I have a string

s = 'abcd qwrre qwedsasd zxcwsacds'

I want to split any string in only two parts at the first occurrence of a whitespace. i.e. a='abcd' and b='qwrre qwedsasd zxcwsacds'

If I use a, b=split(' ') it gives me an error because there are too many values to unpack.

like image 691
Abhishek Velankar Avatar asked Jun 14 '18 02:06

Abhishek Velankar


People also ask

How do I split a string into two parts in SQL?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument. FROM STRING_SPLIT( 'An example sentence.

Can split () take two arguments?

split() only works with one argument, so I have all words with the punctuation after I split with whitespace.

How do you split a string into two substrings in Python?

Python String | split() split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Parameters : separator : This is a delimiter. The string splits at this specified separator.


2 Answers

You could use a,b = split(' ', 1).

The second argument 1 is the maximum number of splits that would be done.

s = 'abcd efgh hijk'
a,b = s.split(' ', 1)
print(a) #abcd
print(b) #efgh hijk

For more information on the string split function, see str.split in the manual.

like image 198
TMK Avatar answered Oct 17 '22 01:10

TMK


From the Python docs

str.split(sep=None, maxsplit=-1)

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).

'1 2 3'.split(maxsplit=1)
# ['1', '2 3']
like image 13
ajxs Avatar answered Oct 17 '22 02:10

ajxs