'How to add spaces in a string [duplicate]
I am using the python module, markovify. I want to make new words instead of making new sentences.
How can I make a function return an output like this?
spacer('Hello, world!') # Should return 'H e l l o , w o r l d !'
I tried the following,
def spacer(text):
for i in text:
text = text.replace(i, i + ' ')
return text
but it returned, 'H e l l o , w o r l d ! ' when I gave, 'Hello, world!'
Solution 1:[1]
- You can use this one.
def spacer(string):
return ' '.join(string)
print(spacer('Hello,World'))
- Or You can change this into.
def spacer(text):
out = ''
for i in text:
out+=i+' '
return out[:-1]
print(spacer("Hello, World"))
- (If you want) You could make the same function into a custom spacer function, But here you also need to pass how many spaces(Default 1) you want in between.
def spacer(string,space=1):
return (space*' ').join(string)
print(spacer('Hello,World',space=1))
- OR FOR CUSTOM SPACES.
def spacer(text,space=1):
out = ''
for i in text:
out+=i+' '*space
return out[:-(space>0) or len(out)]
print(spacer("Hello, World",space=1))
.? OUTPUT.
H e l l o , W o r l d
Solution 2:[2]
The simplest method is probably
' '.join(string)
Since replace works on every instance of a character, you can do
s = set(string)
if ' ' in s:
string = string.replace(' ', ' ')
s.remove(' ')
for c in s:
string = string.replace(c, c + ' ')
if string:
string = string[:-1]
The issue with your original attempt is that you have ox2 and lx3 in your string. Replacing all 'l' with 'l ' leads to l . Similarly for o .
Solution 3:[3]
The simplest answer to this question would be to use this:-
"Hello world".replace("", " ")[1:-1]
This code reads as follows:- Replace every empty substring with a space, and then trim off the trailing spaces.
Solution 4:[4]
print(" ".join('Hello, world!'))
Output
H e l l o , w o r l d !
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | Mad Physicist |
