CYBER WEEK - EXTRA SAVINGS EVENT
TRY A FREE LESSON

String Split Function in Python

I have a problem here

name = "Mohith Jain is my name."

Desired output:

['Mohith Jain', 'is', 'my name.']

My tried solution: I have tried using the split function in Python. Code:

result = name.split()
['Mohith', 'Jain', 'is', 'my', 'name']

I am stuck here and unable to proceed further. I have tried using for loop. But, I am not getting the required result.

Am I missing something or is there any other way of solving this problem?

Please let me know.

I have tried this, A real life example in MS Excel where the string entered in the cell is split based on some delimiter. As i followed the same it was working

One way to accomplish this would be to use str.join() like so:

name = "Mohith Jain is my name."
words = name.split()
result = [' '.join(words[0:2]), words[2], ' '.join(words[3:])]
print(result)

Output:
['Mohith Jain', 'is', 'my name.']

I’m sure there are other ways to solve this problem but this is relatively painless for strings with only a few words.

1 Like

I have tried using the way you mentioned, and I am getting the desired output. Thank you for your help.