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

19th Oct 2020, 8:44 AM
Frost Spectre
Frost Spectre - avatar
7 Answers
+ 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
19th Oct 2020, 9:28 AM
Lothar
Lothar - avatar
+ 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=', ')
19th Oct 2020, 6:10 PM
Lothar
Lothar - avatar
+ 1
Where's your attempt?
19th Oct 2020, 9:17 AM
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ - avatar
+ 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
19th Oct 2020, 2:13 PM
Flash
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)
19th Oct 2020, 12:35 PM
Frost Spectre
Frost Spectre - avatar
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])
19th Oct 2020, 4:15 PM
Frost Spectre
Frost Spectre - avatar
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.
19th Oct 2020, 4:24 PM
Flash