Usuń znaki specjalne z wyjątkiem spacji na liście bez używania re - Python [duplikat]
Dec 02 2020
Mam listę lst = ["is", "star", "the-"] i chcę usunąć znaki ',', '-' bez użycia re.
Użyłem poniżej i działa ale zastanawiałem się czy jest coś prostszego:
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)
Odpowiedzi
1 AziMez Dec 02 2020 at 17:31
Mam nadzieję, że to ci pomoże:
lst = ["is ", "star,", "the-"]
lst = [''.join(e for e in f if e.isalpha()) for f in lst]
print(lst)
Wynik:
['is', 'star', 'the']
ATIFADIB Dec 02 2020 at 17:25
Jeśli interesują Cię tylko małe litery, możesz użyć wbudowanej metody ord w Pythonie.
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)