python百例 --- 提取字符串

有这样的字符串:"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'
    • 列表解析可以将以上代码简化成一行:

      >>> ''.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
原文地址:https://www.cnblogs.com/liangbc/p/12682106.html