4

I need to transform the string:

"There are 6 spaces in this string."

to:

"Thereare6spacesinthisstring."

3 Answers 3

15

You can use replace

string = "There are 6 spaces in this string"
string = string.replace(' ', '')
Sign up to request clarification or add additional context in comments.

1 Comment

LJ3: It's also considered A Good Thing to accept answers by clicking the check mark to the left of the answer, as well as up-vote answers you find useful
4
new = "There are 6 spaces in this old_string.".replace(' ', '')

If you want to strip all whitespace, including tabs:

new = ''.join( old_string.split() )

2 Comments

wouldn't re.subn be better to handle whitespaces? or are the two equivalent?
Thanks had tried the replace version above with no luck, the join split solution is elegant and works like a charm... btw Python 3.2.3
2

You can use replace() :

print(string.replace(" ", ""))

You can also delete white characters at the end / beginning (or both!) with rstrip, lstrip or strip.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.