美文网首页python百例
127-提取字符串

127-提取字符串

作者: 凯茜的老爸 | 来源:发表于2019-07-05 10:51 被阅读98次

有这样的字符串:“123#%4hello*world000”,要求:

  • 将字符串中的所有字母取出来
  • 将字符串中开头的非字母字符去除
    分析:对于提取字母的要求,首先遍历所有的字符串,如果字符串是字母就把它保存到列表中,如果要求结果仍然是字符串,再把它们拼接即可:
>>> s1 = '123#%4hello*world000'
>>> slist = []
>>> for ch in s1:
...     if ch.isalpha():
...         slist.append(ch)
...
>>> print(slist)
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
>>> ''.join(slist)
'helloworld'

列表解析可以将以上代码简化成一行:

>>> [ch for ch in s1 if ch.isalpha()]
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
>>> ''.join([ch for ch in s1 if ch.isalpha()])
'helloworld'

第二个需求是去除字符串开头的非字母字符,这个功能的实现只要找到左边第一字母的下标,然后取切片。
以下通过两个方法完成第二点要求:

  • 直接取下标
>>> s1 = '123#%4hello*world000'
>>> for i in range(len(s1)):
...     if  s1[i].isalpha():
...         break
...
>>> print(s1[i:])
hello*world000
  • 通过enumerate内建函数
>>> s1 = '123#%4hello*world000'
>>> for ind, ch in enumerate(s1):
...     if ch.isalpha():
...         break
...
>>> print(s1[ind:])
hello*world000

相关文章

网友评论

    本文标题:127-提取字符串

    本文链接:https://www.haomeiwen.com/subject/xbdshctx.html