Entfernen Sie Sonderzeichen mit Ausnahme des Leerzeichens in einer Liste, ohne re - Python [duplizieren] zu verwenden.
Dec 02 2020
Ich habe die Liste lst = ["is", "star", "the-"] und möchte ',', '-' entfernen, ohne re zu verwenden.
Ich habe das Folgende benutzt und es funktioniert, aber ich habe mich gefragt, ob es etwas Einfacheres gibt:
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)
Antworten
1 AziMez Dec 02 2020 at 17:31
Hoffe das hilft dir:
lst = ["is ", "star,", "the-"]
lst = [''.join(e for e in f if e.isalpha()) for f in lst]
print(lst)
Ausgabe:
['is', 'star', 'the']
ATIFADIB Dec 02 2020 at 17:25
Wenn Sie nur an Kleinbuchstaben interessiert sind, können Sie die integrierte Ordnungsmethode von Python verwenden.
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)