简体   繁体   中英

How can I remove element from list?

Attempts to remove characters from the string that are not numbers. Unfortunately, I cannot do this due to a reason. I also tried "del file[i][j]", unfortunately without.

Code:

file_open = open("napisy.txt","r")
wyniki = open("wyniki4.txt","w")
file = file_open.read().split()
file1 = file
print(file)
cyfry = ['0','1','2','3','4','5','6','7','8','9']
cyfry_zad3 = ''
licznik_cyfr = 0
tab = []
for i in range(0,len(file1)):
    for j in range(0,len(file1[i])):
        if file1[i][j] not in cyfry:
            file1.remove(file1[i][j])
            #del file1[i][j]
print(file1)

result

在此处输入图像描述

How about making it all simpler?

bad_characters = ['0','1','2','3','4','5','6','7','8','9'] 
file_text = file.read()
file_text = ''.join(filter(lambda c: c not in bad_characters, file_text))

A novice-friendly version:

bad_characters = ['0','1','2','3','4','5','6','7','8','9'] 
file_text = file.read()
good_text = ""
for character in file_text:
    if character not in bad_characters:
        good_text += character 
print(good_text)

You can use this

file_open = open("napisy.txt","r")
file = file_open.read()
file_open.close()

for char in list(file):
    if char not in "1234567890":
        file = file.replace(char, "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM