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条)