Home > OS >  How to replace every space within a text
How to replace every space within a text

Time:09-13

x = input("")
print(str(x), sep="...")

First off this is Python 3. These are the lines of code I have created. I am looking to replace each space with ... When I input Hi I am Mike, the output is Hi I am Mike. I thought that the "sep" part would make the separation ... instead of a space.

So basically I am receiving the exact same input as output and I thought that I would receive Hi...I...am...Mike.

I tried looking on the python source code and on here but it seems everyone is so far above my level that I just cannot find the simplicity I am in need of. What I am I doing wrong?

CodePudding user response:

This doesn't work as sep requires several parameters in print to have an effect.

You have many ways.

split and unpacking:

s = 'Hi I am Mike'
print(*s.split(), sep="...")

split and str.join:

s = 'Hi I am Mike'
print('...'.join(s.split()))

str.replace:

s = 'Hi I am Mike'
print(s.replace(' ', '...'))

Output: Hi...I...am...Mike

CodePudding user response:

The sep only works if you provide multiple strings. Like this:

strings = ["Hi", "I", "am", "Mike"]
print(strings[0],strings[1],strings[2],strings[3], sep="...")

So first split your input on spaces, then combine those with the sep parameter.

my_input = input()
my_input.split()

CodePudding user response:

You can use the replace() method:

string = "Hi I am Mike"
new_string = string.replace(" ", "...")
print(new_string)

And the output is:

Hi...I...am...Mike

CodePudding user response:

You could perhaps use replace if you're looking for simplicity.

The first line declares your input. Always be sure to set your new value, which I'm doing on the second line. The final line prints out the new value, with the replacement done. Worked for me on Python 3.

x = 'Hi I am Mike';

newValue = x.replace(" ", "...");

print(newValue);

  • Related