Let's say I have a user input a string.

string = input("enter a string")

and that string ends up being something like "hello world!" but with a lot more whitespace.

string = "hello     world!"

I want to condense this user's input so that instead of all that whitespace I only get one piece of whitespace ("hello world!") so that I can then replace the whitespace with an underscore ("hello_world!"). How might I go about doing this?

Recommended Answers

All 2 Replies

You can use the re module

>>> import re
>>> string = "hello     world!"
>>> result = re.sub(r'\s+', ' ', string)
>>> print(result)
hello world!

Another way is to split and join

>>> result = ' '.join(string.split())
>>> print(result)
hello world!

Gribouillis' second method would be my chioce:

s = "hello    from  outer        space"
print('_'.join(s.split()))

'''
hello_from_outer_space
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.