This is what I want the code to do:
string = "1 1 1"
#insert code here
output:
>>>1 1 1
Basically I'm trying to create a " " around the special characters. (In this case it's the plus signs)
CodePudding user response:
For the above string you can try this as there is only one special character
print(' '.join(S.split(" ")))
or
print(S.replace(" "," "))
If you have multiple of them then try something like
result = ""
for char in string:
if char in special_chars:
result = " " char " "
else:
result = char
print(result)
CodePudding user response:
You can split them first, and then re-join them
special_char= ' '
string= "1 1 1".split(special_char)
string= f' {special_char} '.join(string)
CodePudding user response:
You can try something like this
import re
string = "1 1 1"
print(re.escape(string).replace("\\"," "))
Here the output that i got
1 1 1
CodePudding user response:
You'll need to better define special characters. But anyway the solution is to .split() the string and then .join() it like that:
my_string = "1 1 1"
delimiter = ' '
my_string = f' {delimiter} '.join(my_string.split(delimiter))
EDIT
Based on your comment here is example for multiple delimiters:
my_string = "1 1-1"
delimiters = [' ', '-']
for delimiter in delimiters
my_string = f' {delimiter} '.join(my_string.split(delimiter))