LJ3
LJ3

Reputation: 41

Removing Spaces from Strings in Python 3.x

I need to transform the string:

"There are 6 spaces in this string."

to:

"Thereare6spacesinthisstring."

Upvotes: 4

Views: 20510

Answers (3)

wkl
wkl

Reputation: 79921

You can use replace

string = "There are 6 spaces in this string"
string = string.replace(' ', '')

Upvotes: 15

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

new = "There are 6 spaces in this old_string.".replace(' ', '')

If you want to strip all whitespace, including tabs:

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

Upvotes: 4

Vincent Savard
Vincent Savard

Reputation: 35927

You can use replace() :

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

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

Upvotes: 2

Related Questions