Python 忽略标点和白色 space
Python ignore punctuation and white space
string = "Python, program!"
result = []
for x in string:
if x not in result:
result.append(x)
print(result)
这个程序使得如果一个重复的字母在一个字符串中被使用了两次,它只会在列表中出现一次。在本例中,字符串“Python, program!”将显示为
['P', 'y', 't', 'h', 'o', 'n', ',', ' ', 'p', 'r', 'g', 'a', 'm', '!']
我的问题是,如何让程序忽略标点符号,例如“. , ; ? !-”以及空格?所以最终输出看起来像这样:
['P', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'g', 'a', 'm']
在将字符附加到列表之前,使用 str.isalnum
作为附加条件检查字符串(字母)是否为字母数字:
string = "Python, program!"
result = []
for x in string:
if x.isalnum() and x not in result:
result.append(x)
print(result)
输出:
['P', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'g', 'a', 'm']
如果您不希望输出中出现数字,请尝试 str.isalpha()
(returns True
如果字符是字母)。
您可以使用 string
模块填写它们。这个内置库包含几个常量,这些常量按顺序引用字符集合,例如字母和空格。
import string
start = "Python, program!" #Can't name it string since that's the module's name
result = []
for x in start:
if x not in result and (x in string.ascii_letters):
result.append(x)
print(result)
string = "Python, program!"
result = []
for x in string:
if x not in result:
result.append(x)
print(result)
这个程序使得如果一个重复的字母在一个字符串中被使用了两次,它只会在列表中出现一次。在本例中,字符串“Python, program!”将显示为
['P', 'y', 't', 'h', 'o', 'n', ',', ' ', 'p', 'r', 'g', 'a', 'm', '!']
我的问题是,如何让程序忽略标点符号,例如“. , ; ? !-”以及空格?所以最终输出看起来像这样:
['P', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'g', 'a', 'm']
在将字符附加到列表之前,使用 str.isalnum
作为附加条件检查字符串(字母)是否为字母数字:
string = "Python, program!"
result = []
for x in string:
if x.isalnum() and x not in result:
result.append(x)
print(result)
输出:
['P', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'g', 'a', 'm']
如果您不希望输出中出现数字,请尝试 str.isalpha()
(returns True
如果字符是字母)。
您可以使用 string
模块填写它们。这个内置库包含几个常量,这些常量按顺序引用字符集合,例如字母和空格。
import string
start = "Python, program!" #Can't name it string since that's the module's name
result = []
for x in start:
if x not in result and (x in string.ascii_letters):
result.append(x)
print(result)