如何从 Python 中的字符串中删除空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20991605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove white spaces from a string in Python?
提问by Ufoguy
I need to remove spaces from a string in python. For example.
我需要从python中的字符串中删除空格。例如。
str1 = "TN 81 NZ 0025"
str1sp = nospace(srt1)
print(str1sp)
>>>TN81NZ0025
采纳答案by Ashwini Chaudhary
Use str.replace:
使用str.replace:
>>> s = "TN 81 NZ 0025"
>>> s.replace(" ", "")
'TN81NZ0025'
To remove all types of white-space characters use str.translate:
要删除所有类型的空白字符,请使用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'
回答by Maxime Lorant
You can replace every spaces by the string.replace()function:
您可以用string.replace()函数替换每个空格:
>>> "TN 81 NZ 0025".replace(" ", "")
'TN81NZ0025'
Or every whitespaces caracthers (included \tand \n) with a regex:
或者每个空格字符(包括\t和\n)都带有正则表达式:
>>> re.sub(r'\s+', '', "TN 81 NZ 0025")
'TN81NZ0025'
>>> re.sub(r'\s+', '', "TN 81 NZ\t0025") # Note the \t character here
'TN81NZ0025'
回答by psun
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,
请注意,在 python 中字符串是不可变的,字符串替换函数返回一个带有替换值的字符串。如果不是在 shell 而是在文件中执行语句,
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,
这将替换字符串中的所有空格。如果只想替换前 n 个空格,
new_str = old_str.replace(" ","", n)
where n is a number.
其中 n 是一个数字。
回答by gabchan
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:
解释:
- Split entire string into list.
- Filter empty elements from list.
- Rejoin remaining elements with nothing
- 将整个字符串拆分为列表。
- 从列表中过滤空元素。
- 什么都不用重新加入剩余的元素
回答by prometeu
Try this:
尝试这个:
s = "TN 81 NZ 0025"
s = ''.join(s.split())
回答by P.Madhukar
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)

