python去字符串空格函数汇总

  • 1 strip()方法,去除字符串开头或者结尾的空格
>>> a = ' hello '
>>> a.strip()
'hello'
  • 2 lstrip()方法,去除字符串开头的空格
>>> a = ' hello '
>>> a.lstrip()
'hello '
  • 3 rstrip()方法,去除字符串结尾的空格
>>> a = ' hello '
>>> a.rstrip()
' hello'
>>> 
  • 4 replace()方法,可以去除全部空格
>>> a = ' he l lo '
>>> a.replace(' ', '')
'hello'
  • 5 join()方法+split()方法,可以去除全部空格
>>> a = ' h el l o '
>>> b = a.split()  # 字符串按照空格分割成列表
>>> b
['h', 'el', 'l', 'o']
>>> c = ''.join(b)  #使用一个空字符串合成列表内容生成新的字符串
>>> c
'hello'

简化一下:

>>> a = ' h el l o '
>>> ''.join(a.split())
'hello'

补充例题:
摘自廖大神的文章例题:
利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法
代码如下:

def trim(s):
    if s == '':
        return s
    while (s[0] == ' '):
        s = s[1:]
    while s[-1] == ' ':
        s = s[:-1]
    return s

print(trim('    hello    '))
print('hello')

以上代码有错误
如果s = ’ '的情况会进行报错。“string index out of range”
修改代码:

def trim(s):
    if s == '':
        return s
    while (s[:1] == ' '):
        s = s[1:]
    while s[-1:] == ' ':
        s = s[:-1]
    return s

print(trim('    hello    '))
print('hello')

本练习只要是复习切片知识,以上内容为扩展。

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值