Reducing code length - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Reducing code length (/thread-4089.html) |
Reducing code length - xavier992 - Jul-21-2017 Hi everyone, I'm new to python and I'm trying to reduce code length. Is there an efficient way to rewrite this simple code? Thanks for the help! Xav def config_WOpick(lst): for k in lst: position=0 if k.startswith('M1CW') or k.startswith('1CW') or k.startswith('CW'): for j in k: position+=1 if j=='W': print(k[position:])#insert the renaming action here later on RE: Reducing code length - Larz60+ - Jul-21-2017 How about some sample input. RE: Reducing code length - ichabod801 - Jul-21-2017 def config_WOpick(lst): for k in lst: if k.startswith('M1CW') or k.startswith('1CW') or k.startswith('CW'): print(k[k.index('W') + 1:]Note that reducing code length is not the same thing as increasing efficiency. You might be able to simplify the if statement, depending on what your population of starting strings is. RE: Reducing code length - snippsat - Jul-22-2017 And startswith() can take a tuple as parameter. if k.startswith(('M1CW', '1CW', 'CW')):
RE: Reducing code length - xavier992 - Jul-22-2017 I'm using a list of string for the input. For example: lst = ['M1CW10006-1','15277782','CW1455778'] etc.. There is more than 100 000 of those kind of string on the list and I take the digits after the letters. I'm just looking to reduce the number of lines of code (to improv my writting efficency as I'm learning) P.S: Thanks for the tip snippsat! |