reを使用せずにリスト内のスペース以外の特殊文字を削除します-Python [duplicate]

Dec 02 2020

リストlst = ["is"、 "star、"、 "the-"]があり、reを使用せずに '、'、 '-'を削除したい。

私は以下を使用しました、そしてそれは働きます、しかし私はもっと簡単な何かがあるかどうか疑問に思いました:

words = []
index = 0
length = 0

for char in lst:
    for i, c in enumerate(char):
        if c.isalpha():
            if length == 0:
                index = i
            length += 1
        else:
            word = char[index:index + length]
            words.append(word)
            length = 0
print(words)

回答

1 AziMez Dec 02 2020 at 17:31

これがお役に立てば幸いです。

lst = ["is ", "star,", "the-"] 
lst = [''.join(e for e in f if e.isalpha()) for f in lst] 
print(lst)

出力:

['is', 'star', 'the']
ATIFADIB Dec 02 2020 at 17:25

小文字のみに関心がある場合は、Pythonの組み込みordメソッドを使用できます。

for idx, word in enumerate(words):
    new_word = ""
    for char in word:
        if char == " " or 97 <= ord(char) <= 122:
            new_word += char
    words[idx] = new_word
bonifacio_kid Dec 02 2020 at 17:35
words = []
for word in lst:
    #clean_word: loop the word and check every single value if it is alphanumeric, append and pass if it is a special characters or spaces. It will become a list since we do list comprehension (['i', 's']) and join them to become a string ('is').
    clean_word = [letter for letter in word if letter.isalnum()]
    words.append(''.join(clean_word))
print (words)