📜  从字符串python中删除空格(1)

📅  最后修改于: 2023-12-03 14:49:23.648000             🧑  作者: Mango

从字符串中删除空格

在Python中,要从字符串中删除空格,有多种方法可供选择。具体方法取决于您的目标和您想使用的工具。

以下是一些通用的方法:

方法一:使用replace()方法

可以使用 Python 中的 replace() 方法将字符串中的空格替换为其他字符,例如空字符串 ''。

string = "   this is a string with  spaces   "
string = string.replace(" ", "")
print(string)  # Output: "thisisastringwithspaces"
方法二:使用join()和split()方法

可以使用 Python 中的 join() 和 split() 方法将字符串拆分为单词,再将单词合并为没有空格的字符串。

string = "   this is a string with  spaces   "
string = "".join(string.split())
print(string)  # Output: "thisisastringwithspaces"
方法三:使用正则表达式

可以使用 Python 中的 re 模块和正则表达式来删除字符串中的空格。

import re

string = "   this is a string with  spaces   "
string = re.sub(r"\s+", "", string)
print(string)  # Output: "thisisastringwithspaces"

以上就是三种常见的方法,可以根据自己的需求选择最适合的方法。更多关于字符串操作和正则表达式的内容,请参考Python官方文档。