Python: Split String Without Losing Split Character [Duplicate]

string = 'Hello.World.!'

My Try

string.split('.')

Output

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

Goal Output

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

0

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

import re
string = 'Hello.World.!'

re.split(r'(\.)', string)
# ['Hello', '.', 'World', '.', '!']

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?

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()
1

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] 

1
David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest