打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python 中删除字符串中的所有空格的8种方法

1. 使用Python的replace()方法

删除空格的一种直接方法是使用replace()方法。

original_string = 'Hello, World!'no_whitespace = original_string.replace(' ', '')print(no_whitespace) # Output: 'Hello,World!'

2. 使用正则表达式

正则表达式提供了一种强大而灵活的方法来处理空格删除:

import reoriginal_string = 'Remove all whitespace from this string'no_whitespace = re.sub(r'\s', '', original_string)print(no_whitespace)  # Output: 'Removeallwhitespacefromthisstring'

3. 使用列表理解

列表推导式提供了一个方便灵活的解决方案:

original_string = 'Python is amazing'no_whitespace = ''.join(original_string.split())print(no_whitespace) # Output: 'Pythonisamazing'”

4.使用join()方法

使用该oin()方法的另一种方法:

original_string = 'Let's remove spaces'words = original_string.split()no_whitespace = ''.join(words)print(no_whitespace)  # Output: 'Let'sremovespaces'

5.使用split()及join()方法

可以使用split()join()的组合:

original_string = 'Split and Join'no_whitespace = ' '.join(original_string.split())print(no_whitespace) # Output: 'Split and Join'

6. 使用filter()和str.isspace()

使用filter()with 函数str.isspace()来删除空格:

original_string = '   Filter spaces   'no_whitespace = ''.join(filter(lambda x: not x.isspace(), original_string))print(no_whitespace)  # Output: 'Filterspaces'

87 删除两端的空格

要删除字符串两端的空格,请使用strip()

original_string = ' Strip spaces 'no_whitespace = original_string.strip()print(no_whitespace) # Output: 'Strip spaces'

9. 处理多行字符串

要从多行字符串中删除空格,用splitlines()and join()

multiline_string = '''Line 1Line 2Line 3'''no_whitespace = '\n'.join(line.strip() for line in multiline_string.splitlines())print(no_whitespace)
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python3 反序有空格字符串
Python 字符串处理备忘单
Python如何去掉字符串的空格?
python技巧 - 连接字符串的 6 种方法
Javascript删除表单空格和连续的空格代码
Python生成8位随机字符串的一些方法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服