+ 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.
8 Antworten
+ 9
rodwynnejones, you did it! This is the most simple way. I was not aware of the second argument.
+ 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']
+ 7
a = "Hi, this is kiran"
print(a.split(' ', 1))
+ 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']
+ 4
U Know that each but last item has a comma at last character
for I in len(a)-1:
a[i]+=","
+ 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 👍
+ 1
sudo-asap would use insert or use split in the way rodwynnejones has
- 1
#