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

소문자에만 관심이 있다면 빌드 된 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)