I have a list of strings.
theList = ['a', 'b', 'c']
I want to add integers to the strings, resulting in an output like this:
newList = ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3']
I want to save this to a .txt file, in this format:
a0
b0
c0
a1
b1
c1
a2
b2
c2
a3
b3
c3
The attempt:
theList = ['a', 'b', 'c']
newList = []
for num in range(4):
stringNum = str(num)
for letter in theList:
newList.append(entry+stringNum)
with open('myFile.txt', 'w') as f:
print>>f, newList
Right now I can save to the file myFile.txt but the text in the file reads:
['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3']
Any tips on more pythonic ways to achieve my goal are very welcome,
Instead of your last line, use:
f.write("\n".join(newList))
This will write the strings in newList, separated by newlines, to f. Note that if you don't actually need newList, you can combine your two loops and write the strings as you go:
the_list = ['a', 'b', 'c']
with open('myFile.txt', 'w') as f:
for num in range(4):
for letter in the_list:
f.write("%s%s\n" % (letter, num))
If you want to compress your code a little bit you can do:
>>> n = 4
>>> the_list = ['a', 'b', 'c']
>>> new_list = [x+str(y) for x in the_list for y in range(n)]
>>> with open('myFile.txt', 'w') as f:
... f.write("\n".join(new_list))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With