1

string = 'Hello.World.!'

My Try

string.split('.')

Output

['Hello', 'World', '!']

Goal Output

['Hello', '.', 'World', '.', '!']

4 Answers4

2

You can do this:

string = 'Hello.World.!'

result = []
for word in string.split('.'):
    result.append(word)
    result.append('.')

# delete the last '.'
result = result[:-1]

You can also delete the last element of the list like that:

result.pop()
D_00
  • 1,440
  • 2
  • 13
  • 32
2

Use re.split and put a capturing group around the separator:

import re
string = 'Hello.World.!'

re.split(r'(\.)', string)
# ['Hello', '.', 'World', '.', '!']
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
2

Use re.split(), with first arg as your delimiter.

import re

print(re.split("(\.)", "hello.world.!"))

Backslash is to escape the “.” as it is a special character in regex, and parentheses to capture the delimiter as well.

Related question: In Python, how do I split a string and keep the separators?

Anson Miu
  • 1,171
  • 7
  • 6
0

If you want to do this in a single line:


string = "HELLO.WORLD.AGAIN."
pattern = "."
result = string.replace(pattern, f" {pattern} ").split(" ")
# if you want to omit the last element because of the punctuation at the end of the string uncomment this
# result = result[:-1] 

Farhood ET
  • 1,432
  • 15
  • 32