python中去掉字符串中的空格

我们想去除字符串中不必要的空格时可以使用如下方法:

在这里以str作为例子来演示。在str中前中后三处都有空格。

函数原型:

声明:str为字符串,rm为要删除的字符序列

  • str.strip(rm) : 删除s字符串中开头、结尾处,位于 rm删除序列的字符

  • str.lstrip(rm) : 删除s字符串中开头(左边)处,位于 rm删除序列的字符

  • str.rstrip(rm) : 删除s字符串中结尾(右边)处,位于 rm删除序列的字符

  • str.replace(‘s1’,’s2’) : 把字符串里的s1替换成s2。故可以用replace(’ ‘,”)来去掉字符串里的所有空格

  • str.split() : 通过指定分隔符对字符串进行切分,切分为列表的形式。

  • 去除两边空格:

>>> str = ' hello world '
>>> str.strip()
'hello world'
  • 去除开头空格:
>>> str.lstrip()
'hello world '
  • 去除结尾空格:
>>> str.rstrip()
' hello world'
  • 去除全部空格:
>>> str.replace(' ','')
'helloworld'
  • 将字符串以空格分开:
>>> str.split()
['hello', 'world']
>>> 
### Python去除字符串空格的函数 在 Python 中,可以使用多种方法来去除字符串中的空格。以下是几种常用的方法: #### 使用 `strip()` 方法 `strip()` 可以移除字符串开头和结尾处的空白字符(包括空格、制表符 `\t` 和换符 `\n`),但不会影响中间的空格。 ```python str = " Hello, world! " cleaned_str = str.strip() print(cleaned_str) # 输出:'Hello, world!' ``` 此方法适用于需要清理字符串两端多余空格的情况[^3]。 #### 使用 `lstrip()` 和 `rstrip()` 方法 - `lstrip()` 移除字符串左侧的空白字符。 - `rstrip()` 移除字符串右侧的空白字符。 ```python left_cleaned_str = str.lstrip() right_cleaned_str = str.rstrip() print(left_cleaned_str) # 输出:'Hello, world! ' print(right_cleaned_str) # 输出:' Hello, world!' ``` 这两种方法分别针对字符串的一端进处理[^1]。 #### 使用 `replace()` 方法 当目标是从整个字符串中删除所有的空格时,可采用 `replace()` 方法替换所有出现的空格为空字符串。 ```python no_space_str = str.replace(" ", "") print(no_space_str) # 输出:'Hello,world!' ``` 这种方法会作用于整个字符串内的每一个空格位置。 #### 组合使用 `split()` 和 `''.join()` 对于更复杂的场景,比如想要保留单词间的单个空格同时消除多余的连续空格,可以通过先拆分再重新组合的方式达成目的。 ```python normalized_str = ''.join(str.split()) print(normalized_str) # 输出:'Hello,world!' ``` 这种方式不仅能够有效去除不必要的空隙,还能确保最终结果更加整洁有序。 综上所述,在不同情况下可以根据具体需求选用合适的去空格方式。每种方法都有其特点和适用范围,合理选择能提高编程效率并简化代码逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值