Python3 处理字符串中的空格

处理字符串首尾字符串
1. str.strip([char]) 删除字符串char字符
2. str.rstrip([char]) 删除字符串右边char字符
3. str.lstrip([char]) 删除字符串左边char字符
4. str.split(sep=None, maxsplit=-1) 切分字符串,maxsplit为-1时表示切分次数无限制
5. str.replace(old, new,[,count]) 字符串指定替换,count未指定时默认替换所有
6. re.sub(pattern,repl,string,count=0, flags=0) 字符串替换 类似于replace()
7. slice() 切片

>>> s = " test testa "
>>> s.strip()
'test testa'
>>> s.strip(' a')
'test test'
>>> s.rstrip()
' test testa'
>>> s.rstrip(' a')
' test test'
>>> s.split()
['test', 'testa']
>>> s.replace(' ','')
'testtesta'
>>> re.sub(r' ', r'', s)
'testtesta'

Reference:
https://docs.python.org/3/

### Python处理字符串空格的方法 在 Python 中,可以通过内置函数以及自定义逻辑来处理字符串中的空格。以下是几种常见的方法: #### 使用 `strip()` 方法 `strip()` 是一种用于移除字符串两端(开头和结尾)空白字符(包括空格、制表符 `\t` 和换行符 `\n`)的内置方法[^2]。此方法不会影响字符串中间的任何空格。 ```python s = " Hello, World! " result = s.strip() print(result) # 输出:"Hello, World!" ``` #### 自定义实现去除首尾空格的功能 如果希望手动实现类似于 `strip()` 的功能,可以编写如下代码[^1]: ```python def custom_strip(s): start = 0 end = len(s) while start < end and s[start].isspace(): start += 1 while end > start and s[end - 1].isspace(): end -= 1 return s[start:end] s = " Hello, World! " result = custom_strip(s) print(result) # 输出:"Hello, World!" ``` #### 替换字符串中的所有空格 为了替换字符串中的所有空格,可以使用 `replace()` 方法。该方法接受两个参数:第一个是要被替换的部分,第二个是替换成的内容。 ```python s = "Hello, World! This is a test." result = s.replace(" ", "-") print(result) # 输出:"Hello,-World!-This-is-a-test." ``` #### 去除字符串中的多余空格并保留单个空格 有时可能需要清理字符串中多余的连续空格,并仅保留单词之间的单一空格。这可以通过正则表达式完成: ```python import re s = "Hello, World! This is a test. " result = re.sub(r&#39;\s+&#39;, &#39; &#39;, s).strip() print(result) # 输出:"Hello, World! This is a test." ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值