0
[Python] Need Help in removing characters [ and ] from list of strings
Am new with lists in python programming. Will need help in writing a program that: - Prompts input from user till an empty string is given - Removes [ and ] from filenames and prints a string with separated by commas Test input: cute_cat[20150203].jpg [quick] brown_fox.png [x264] lazy_dog [1280x720].mp4 Output: cute_cat.jpg, brown_fox.png, lazy_dog.mp4
7 odpowiedzi
+ 9
To give you a hint:
removing the squared brackets can be done with one of these approaches:
- use string method replace()
- use a for loop to check for the brackets and skip them by creating a new string
- use regular expression
+ 7
here is a sample how replace works:
...
new_filename = []
for word in filename:
word = word.replace('[','')
word = word.replace(']','')
new_filename.append(word)
print(*new_filename, sep=', ')
+ 1
Where's your attempt?
+ 1
here:
'''
Flash
Oct 19, 2020
input:
an empty string [just press submit button]
output:
cute_cat.jpg, brown_fox.png, lazy_dog.mp4
'''
import re
def get_input():
ret = []
i = input()
while i != '':
ret.append(i)
i = input()
return ret
def process_filename(list_names):
if len(list_names) < 1:
return ''
return ', '.join([re.sub(r"\[([A-Za-z0-9_]+)\]", '', i.strip().replace(' ', '')) for i in list_names])
#this won't work on sololearn
#l = get_input()
l = ['cute_cat[20150203].jpg\n', '[quick] brown_fox.png\n', '[x264] lazy_dog [1280x720].mp4\n']
print(process_filename(l))
https://code.sololearn.com/caG7PLYg50c8/?ref=app
0
Sorry am pretty new. Am only able to create the list and input part. I dont know how to remove items within [] yet. Any suggestions on how to continue.
Test input: cute_cat[20150203].jpg ([20150203] has to be removed)
filename = []
while True:
fileinput = input("Filename? ")
if fileinput == "":
break
else:
filename.append(fileinput)
print(filename)
0
How can i integrate your code into mine. The program I am working on should be able to cull any input that has [] as well as the contents stored in [].
Also can i check what this string means:
return ', '.join([re.sub(r"\[([A-Za-z0-9_]+)\]", '', i.strip().replace(' ', '')) for i in list_names])
0
Frost Spectre the code I posted should work on the condition you mentioned. it’s a reg exp. the line simply removes whitespaces(\n...), spaces, then replaces [...] with nothing from a given string.