有這樣的字符串:“123#%4hello*world000”诬辈,要求:
- 將字符串中的所有字母取出來(lái)
- 將字符串中開頭的非字母字符去除
分析:對(duì)于提取字母的要求,首先遍歷所有的字符串赃承,如果字符串是字母就把它保存到列表中盔然,如果要求結(jié)果仍然是字符串议纯,再把它們拼接即可:
>>> 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'
列表解析可以將以上代碼簡(jiǎn)化成一行:
>>> [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'
第二個(gè)需求是去除字符串開頭的非字母字符晚缩,這個(gè)功能的實(shí)現(xiàn)只要找到左邊第一字母的下標(biāo)笼才,然后取切片漱受。
以下通過(guò)兩個(gè)方法完成第二點(diǎn)要求:
- 直接取下標(biāo)
>>> s1 = '123#%4hello*world000'
>>> for i in range(len(s1)):
... if s1[i].isalpha():
... break
...
>>> print(s1[i:])
hello*world000
- 通過(guò)enumerate內(nèi)建函數(shù)
>>> s1 = '123#%4hello*world000'
>>> for ind, ch in enumerate(s1):
... if ch.isalpha():
... break
...
>>> print(s1[ind:])
hello*world000