Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python split by number of times specified

Tags:

python

In the following string how can i split the string in the following manner

str1="hi\thello\thow\tare\tyou"
str1.split("\t")
n=1
Output=["hi"]

 n=2 
output:["hi","hello"]
like image 346
Rajeev Avatar asked Dec 12 '22 18:12

Rajeev


1 Answers

str1.split('\t', n)[:-1]

str.split has an optional second argument which is how many times to split. We remove the last item in the list (the leftover) with the slice.

For example:

a = 'foo,bar,baz,hello,world'
print(a.split(',', 2))
# ['foo', 'bar', 'baz,hello,world']  #only splits string twice
print(a.split(',', 2)[:-1])  #removes last element (leftover)
# ['foo', 'bar']
like image 51
Volatility Avatar answered Jan 06 '23 06:01

Volatility