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"]
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With