+ 3

How can I actually do this ?

a="Hi, this is kiran" print(a.split(',')) This code gives the output as ['Hi', 'this is kiran'] But instead I want the output as ['Hi,', 'this is kiran']. Can this actually be possible ? If yes please give an explanation with the program.

23rd Apr 2020, 11:42 AM
Kiran Deep Naidu
Kiran Deep Naidu - avatar
8 Antworten
+ 9
rodwynnejones, you did it! This is the most simple way. I was not aware of the second argument.
23rd Apr 2020, 7:09 PM
Lothar
Lothar - avatar
+ 8
This is the other solution i mentioned, iwth using index and slicing: a = "Hi, this is kiran" print([a[:a.index(', ')+1]] + [a[a.index(', ')+2:]]) # the output is: # ['Hi,', 'this is kiran']
23rd Apr 2020, 4:53 PM
Lothar
Lothar - avatar
+ 7
a = "Hi, this is kiran" print(a.split(' ', 1))
23rd Apr 2020, 6:32 PM
rodwynnejones
rodwynnejones - avatar
+ 5
There seems to be a possible solution by using partition() instead of split(). partition returns a tuple of 3 parts: (1) the string from start upto the separator, (2) the separator itself (3) the rest of the string from separator upto the end. WhT you have to do after this, is to remove index 1 from the tuple: An other solution can be: find the first occurrence of ', ' - then use this index value to separate the string. a = "Hi, this is kiran" res = [i for i in a.partition(' ')] res.pop(1) print(res) # the output is: #['Hi,', 'this is kiran']
23rd Apr 2020, 4:18 PM
Lothar
Lothar - avatar
+ 4
U Know that each but last item has a comma at last character for I in len(a)-1: a[i]+=","
23rd Apr 2020, 12:20 PM
Oma Falk
Oma Falk - avatar
+ 3
It's not possible... You given as a.split(',') whenever the compiler see this statement, it splits the string where it encounter comma... It won't result like ['Hi,', 'this is kiran'] Hope you understand 👍
23rd Apr 2020, 11:50 AM
sarada lakshmi
sarada lakshmi - avatar
+ 1
sudo-asap would use insert or use split in the way rodwynnejones has
24th Apr 2020, 8:20 PM
sudo-asap
sudo-asap - avatar
- 1
#
25th Apr 2020, 8:23 AM
Divya R
Divya R - avatar