Python字符串去除空格的五种方法

Python字符串去除空格的五种方法


2024年1月7日发(作者:)

Python字符串去除空格的五种方法

1. 使用strip(方法去除字符串两端的空格:

```python

string = " Hello World "

new_string =

print(new_string) # Output: "Hello World"

```

2. 使用replace(方法将字符串中的空格替换为空字符串:

```python

string = " Hello World "

new_string = e(" ", "")

print(new_string) # Output: "HelloWorld"

```

3. 使用split(函数将字符串按照空格分割成多个子字符串,然后使用join(函数将这些子字符串连接起来:

```python

string = " Hello World "

new_string = "".join(()

print(new_string) # Output: "HelloWorld"

```

4. 使用正则表达式(函数去除字符串中的空格:

```python

import re

string = " Hello World "

new_string = (r"s+", "", string)

print(new_string) # Output: "HelloWorld"

```

```python

string = " Hello World "

new_string = "".join([char for char in string if char != "

"])

print(new_string) # Output: "HelloWorld"


发布者:admin,转转请注明出处:http://www.yc00.com/web/1704567167a1358074.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信