4

I need to remove spaces from a string in python. For example.

str1 = "TN 81 NZ 0025"

str1sp = nospace(srt1)

print(str1sp)

>>>TN81NZ0025
2

6 Answers 6

27

Use str.replace:

>>> s = "TN 81 NZ 0025"
>>> s.replace(" ", "")
'TN81NZ0025'

To remove all types of white-space characters use str.translate:

>>> from string import whitespace
>>> s = "TN 81   NZ\t\t0025\nfoo"
# Python 2
>>> s.translate(None, whitespace)
'TN81NZ0025foo'
# Python 3
>>> s.translate(dict.fromkeys(map(ord, whitespace)))
'TN81NZ0025foo'
Sign up to request clarification or add additional context in comments.

Comments

5

You can replace every spaces by the string.replace() function:

>>> "TN 81 NZ 0025".replace(" ", "")
'TN81NZ0025'

Or every whitespaces caracthers (included \t and \n) with a regex:

>>> re.sub(r'\s+', '', "TN 81 NZ 0025")
'TN81NZ0025'
>>> re.sub(r'\s+', '', "TN 81 NZ\t0025")  # Note the \t character here
'TN81NZ0025'

Comments

2

Try this:

s = "TN 81 NZ 0025"
s = ''.join(s.split())

Comments

1

Mind that in python strings are immutable and string replace function returns a string with the replaced value. If you are not executing the statement at the shell but inside a file,

 new_str = old_str.replace(" ","" )

This will replace all the white spaces in the string. If you want to replace only the first n white spaces,

new_str = old_str.replace(" ","", n)

where n is a number.

Comments

1

One line of code to remove all extra spaces before, after, and within a sentence:

string = "  TN 81 NZ 0025  "
string = ''.join(filter(None,string.split(' ')))

Explanation:

  1. Split entire string into list.
  2. Filter empty elements from list.
  3. Rejoin remaining elements with nothing

Comments

0

You can replace multiple spaces into a desired pattern by using following ways. Here your pattern is blank string.

import re
pattern = ""
re.sub(r"\s+", pattern, your_string)

or

import re
pattern = ""
re.sub(r" +", "", your_string)

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.