如何从字符串中删除所有空格
如何去除Python字符串中的所有空格?例如,我想要将 strip my space
这样的字符串转换为 stripmyspaces
,但我似乎无法使用 strip()
来实现这一点:
>>> 'strip my spaces'.strip()
'strip my spaces'
How do I strip all the spaces in a python string? For example, I want a string like strip my spaces
to be turned into stripmyspaces
, but I cannot seem to accomplish that with strip()
:
>>> 'strip my spaces'.strip()
'strip my spaces'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
利用 str.split 不带 sep 参数的行为:
如果您只想删除空格而不是所有空白:
过早优化
尽管效率不是主要目标(编写清晰的代码才是),但这里有一些初始计时:
注意正则表达式被缓存了,所以它并不像你想象的那么慢。提前编译它会有所帮助,但只有在实践中调用此很多次时才有意义:
尽管 re.sub 慢了 11.3 倍,但请记住您的瓶颈肯定在其他地方。大多数程序不会注意到这 3 个选择之间的差异。
Taking advantage of str.split's behavior with no sep parameter:
If you just want to remove spaces instead of all whitespace:
Premature optimization
Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:
Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:
Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.
对于 Python 3:
...处理您没有想到的任何空白字符 - 相信我们,有很多。
\s
本身始终覆盖 ASCII 空白:(另外:
re 的 Python 2。启用 UNICODE
,...
\s
还涵盖 Unicode 空白字符,例如:.. 。ETC。请参阅此处“具有 White_Space 属性的 Unicode 字符”下的完整列表。
但是
\s
不涵盖未归类为空白的字符,这些字符实际上是空白,例如:...等。请参阅此处“不带 White_Space 属性的相关 Unicode 字符”下的完整列表。
因此,这 6 个字符被第二个正则表达式
\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF
中的列表覆盖。来源:
For Python 3:
...handles any whitespace characters that you're not thinking of - and believe us, there are plenty.
\s
on its own always covers the ASCII whitespace:Additionally:
re.UNICODE
enabled,...
\s
also covers the Unicode whitespace characters, for example:...etc. See the full list here, under "Unicode characters with White_Space property".
However
\s
DOES NOT cover characters not classified as whitespace, which are de facto whitespace, such as among others:...etc. See the full list here, under "Related Unicode characters without White_Space property".
So these 6 characters are covered by the list in the second regex,
\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF
.Sources:
或者,
这是 Python3 版本:
Alternatively,
And here is Python3 version:
删除Python中的起始空格
删除Python中的尾部或结尾空格
删除Python中字符串开头和结尾的空格
删除Python中的所有空格
Remove the Starting Spaces in Python
Remove the Trailing or End Spaces in Python
Remove the whiteSpaces from Beginning and end of the string in Python
Remove all the spaces in python
最简单的是使用替换:
或者,使用正则表达式:
The simplest is to use replace:
Alternatively, use a regular expression:
正如 Roger Pate 所提到的,以下代码对我有用:
我正在使用 Jupyter Notebook 运行以下代码:
As mentioned by Roger Pate following code worked for me:
I am using Jupyter Notebook to run following code:
尝试使用
re.sub
进行正则表达式。您可以搜索所有空格并替换为空字符串。模式中的
\s
将匹配空白字符 - 而不仅仅是空格(制表符、换行符等)。您可以在手册中阅读更多相关信息。Try a regex with
re.sub
. You can search for all whitespace and replace with an empty string.\s
in your pattern will match whitespace characters - and not just a space (tabs, newlines, etc). You can read more about it in the manual.过滤列表的标准技术适用,尽管它们不如
split/join
或translate
方法高效。我们需要一组空格:
filter
内置:列表理解(是的,使用括号:请参阅下面的基准):
折叠:
基准:
The standard techniques to filter a list apply, although they are not as efficient as the
split/join
ortranslate
methods.We need a set of whitespaces:
The
filter
builtin:A list comprehension (yes, use the brackets: see benchmark below):
A fold:
Benchmark:
一行代码:
Final line of code:
如果不需要最佳性能并且您只想要一些非常简单的东西,您可以定义一个基本函数来使用字符串类的内置“isspace”方法来测试每个字符:
以这种方式构建
no_white_space
字符串将没有理想的性能,但解决方案很容易理解。如果您不想定义函数,可以将其转换为与列表理解大致相似的内容。借用最佳答案的
join
解决方案:If optimal performance is not a requirement and you just want something dead simple, you can define a basic function to test each character using the string class's built in "isspace" method:
Building the
no_white_space
string this way will not have ideal performance, but the solution is easy to understand.If you don't want to define a function, you can convert this into something vaguely similar with list comprehension. Borrowing from the top answer's
join
solution:TL/DR
此解决方案已使用 Python 3.6 进行测试
要从 Python3 中的字符串中去除所有空格,您可以使用以下函数:
删除任何空白字符 (' \t\n\r\x0b\x0c ') 你可以使用以下函数:
Explanation
Python 的
str.translate
方法是 str 的内置类方法,它接受一个表并返回字符串的副本通过传递的翻译表映射每个字符。 str.translate 的完整文档创建翻译表 <使用代码>str.maketrans。该方法是
str
的另一个内置类方法。在这里,我们仅使用一个参数,在本例中是一个字典,其中键是要替换的字符,映射到具有字符替换值的值。它返回一个与str.translate
一起使用的翻译表。 str.maketrans 的完整文档string< python中的/code>模块包含一些常见的字符串操作和常量。
string.whitespace
是一个常量,它返回包含所有被视为空白的 ASCII 字符的字符串。这包括字符空格、制表符、换行符、回车符、换页符和垂直制表符。 string.whitespace 的完整文档在第二个函数中
dict.fromkeys
用于创建一个字典,其中键是string.whitespace
返回的字符串中的字符,每个字符的值为None
。 dict.fromkeys 的完整文档TL/DR
This solution was tested using Python 3.6
To strip all spaces from a string in Python3 you can use the following function:
To remove any whitespace characters (' \t\n\r\x0b\x0c') you can use the following function:
Explanation
Python's
str.translate
method is a built-in class method of str, it takes a table and returns a copy of the string with each character mapped through the passed translation table. Full documentation for str.translateTo create the translation table
str.maketrans
is used. This method is another built-in class method ofstr
. Here we use it with only one parameter, in this case a dictionary, where the keys are the characters to be replaced mapped to values with the characters replacement value. It returns a translation table for use withstr.translate
. Full documentation for str.maketransThe
string
module in python contains some common string operations and constants.string.whitespace
is a constant which returns a string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab. Full documentation for string.whitespaceIn the second function
dict.fromkeys
is used to create a dictionary where the keys are the characters in the string returned bystring.whitespace
each with valueNone
. Full documentation for dict.fromkeys这是使用普通旧列表理解的另一种方法:
示例:
Here's another way using plain old list comprehension:
Example:
这是在采访中被问到的。因此,如果您必须仅使用剥离法来给出解决方案。这是一个方法 -
This got asked in an interview. So if you have to give a solution just by using strip method. Here's an approach -