On 07/12/2020 16:48, Bischoop wrote:
I worked on my wee script that replaces a letters: https://bpa.st/OYBQ .
I would like to have some suggestions about the code from more
experienced programmers, the code does work and do its job but perhaps
could work in a better way.
Thanks
Sure!
First of all, the code could be simplified by using the replace() method
of the str class
(https://docs.python.org/3/library/stdtypes.html#str.replace).
Now a few comments on the code specifically:
while True:
What is this for? It looks like all it does is cause the program to get
caught in an infinite loop if there's an exception...
for element in word_list:
for x in change_this_list:
You can loop over strings as well - there's no need to convert them to
lists.
to = word_list.index(element)
There's a nice trick to get the index while looping: write
for (idx, character) in enumerate(word):
then you don't have to use the index method. This also works if a
character appears multiple times in the word, in which case I think your
code will fail (but I haven't tried it)
(Obviously apply this to the other loop as well, mutadis mutandis, to
get rid of both index() calls)
word_list[to] = replace_with_list[replace]
Okay, this is something you can't do with a str because they're
immutable. Generally I'd avoid modifying the thing you're looping over;
it works in this case when you're replacing elements of a list, but it
probably won't do what you want if you're deleting or adding items.
I'd put
new_word_list = []
somewhere at the top, and build it up element by element with
new_word_list.append(). But what you're doing is fine too as long as you
keep in mind that changing the thing you're looping over can be
dangerous in other cases.
Hope this helps
Thomas
--
https://mail.python.org/mailman/listinfo/python-list