+ 2

Append 3 digit sequence to lines in file

Say I open a file and for each duplicate line appends a three-digit string. For example if in my file there are three instances of Nelson I want the output to read Nelson001 Nelson002 Nelson003 As of now my code only outputs a single digit suffix (ie Nelson1). So how can I use a range of 001 - 00x, instead of 1-x?

16th Feb 2017, 11:10 PM
Aaron Nelson
Aaron Nelson - avatar
5 Answers
+ 3
if you have a loop for the appendix, check if it's less than ten, if so add two zeros as string to the appendix, if it's between ten and one hundred, add one zero.
16th Feb 2017, 11:48 PM
Mario L.
Mario L. - avatar
+ 3
Mario implementing your loop idea actually worked perfectly. Thanks for the suggestion, I can't imagine why I couldn't think of that. Marvin, thanks for the suggestion, however it is a bit bulky for my little script.
17th Feb 2017, 1:18 AM
Aaron Nelson
Aaron Nelson - avatar
+ 2
#User001 User002 User003 usr_input=input("") assignment_num=1 zeroes="00" def num_assign(name): global assignment_num res=str(name) + "-" + zeroes + str(assignment_num) assignment_num +=1 return res while assignment_num<101: print(num_assign(usr_input)) if assignment_num==10: zeroes="0" if assignment_num==100: zeroes=""
17th Feb 2017, 12:38 AM
MemeSenpai
MemeSenpai - avatar
+ 2
Aaron, although Mario's suggestion is much simpler, Marvin's response allows for growth if the number of users is higher than 100. It is also scalable since you can change the behavior of the while loops if a number exceeds a certain threshold. Overall it is more robust if the code you are writing increases in complexity.
17th Feb 2017, 3:05 PM
suprematis
suprematis - avatar
+ 1
yes I can see the merit in Marvin's code and upvoted it for that reason, however since I'm pretty new to Python I'm not sure I would even know how to implement it correctly. The purpose of my script is purely for practice and basically parses my user name out of various log files on my computer. When I get more comfortable with the code and syntax, then I will try to use more pythonic functions and what not. Baby steps lol
17th Feb 2017, 3:42 PM
Aaron Nelson
Aaron Nelson - avatar