Reputation: 59
files = "a.txtb.txt"
if files.find( ".txt" ) != -1:
files = files.split( ".txt" )
files.remove( "" )
[ file + ".txt" for file in files ]
print( files )
I'm new to python. The output I want is the list files = [a.txt, b.txt] in the end, but for testing reasons I have to do all that stuff in the front first. I don't understand why the string cannot be appended to all the elements in my list.
Upvotes: 0
Views: 284
Reputation: 268
You could do the following to obtain the desired result:
files = "a.txt, b.txt"
results = files.split( ',' )
After this, results will contain the desired result in the form of a list.
Upvotes: -1
Reputation: 16711
Use a non-greedy regular expression to find the contained text files:
files = re.findall(r'\w+?\.txt', file_string)
Upvotes: 2
Reputation: 21609
You need to assign the list back to files
. As it stands it just throws the list with the appended values away.
e.g.
files = [ file + ".txt" for file in files ]
Upvotes: 2