I need to remove spaces from a string in python. For example.
str1 = \"TN 81 NZ 0025\"
str1sp = nospace(srt1)
print(str1sp)
>>>TN81NZ0025
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'
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.
Try this:
s = "TN 81 NZ 0025"
s = ''.join(s.split())
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'
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:
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)