How can Python extract letters from a string?
The isalpha() method can be used to determine if the characters in a string are letters and extract them.
string = "Hello, World! 123"
# 提取字符串中的字母
letters = [char for char in string if char.isalpha()]
# 打印提取出的字母
print(letters)
Output:
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
The code above uses a list comprehension to iterate through each character in a string, using the isalpha() method to determine if the character is a letter. If it is a letter, it is added to a new list. Finally, the extracted letter list is printed.