Python: Split string without losing split character [duplicate]

string = 'Hello.World.!'

My Try

string.split('.') 

Output

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

Goal Output

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

0

4 Answers

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

You Might Also Like