Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace multiple spaces with just one character?

Here's my code so far:

input1 = input("Please enter a string: ")
newstring = input1.replace(' ','_')
print(newstring)

So if I put in my input as:

I want only    one     underscore.

It currently shows up as:

I_want_only_____one______underscore.

But I want it to show up like this:

I_want_only_one_underscore.
like image 866
ajkey94 Avatar asked Mar 07 '13 00:03

ajkey94


1 Answers

This pattern will replace any groups of whitespace with a single underscore

newstring = '_'.join(input1.split())

If you only want to replace spaces (not tab/newline/linefeed etc.) it's probably easier to use a regex

import re
newstring = re.sub(' +', '_', input1)
like image 136
John La Rooy Avatar answered Oct 04 '22 19:10

John La Rooy