# 示例代码:去除字符串中的空格
# 方法1:使用 replace() 方法去除所有空格
text = " Hello World "
no_spaces_text = text.replace(" ", "")
print(no_spaces_text) # 输出: HelloWorld
# 方法2:使用 strip() 方法去除首尾空格
text = " Hello World "
stripped_text = text.strip()
print(stripped_text) # 输出: Hello World
# 方法3:使用 split() 和 join() 方法去除所有空格
text = " Hello World "
no_spaces_text = ''.join(text.split())
print(no_spaces_text) # 输出: HelloWorld
# 方法4:使用正则表达式去除所有空格
import re
text = " Hello World "
no_spaces_text = re.sub(r"\s+", "", text)
print(no_spaces_text) # 输出: HelloWorld
re.sub() 函数,通过正则表达式 \s+ 匹配一个或多个空白字符(包括空格、制表符等),并将其替换为空字符串。上一篇:python构造函数
下一篇:python hex
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站