On 2020-12-07 15: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


> word = input( f'input word you want to change letters in: ')

There's no need for the f prefix.

> print(f' Your word to change: ,{word}')

Is the comma a typo?

> word_list = list(word)
> change_this = input(f'Enter the letters you want to change: ')

There's no need for the f prefix.

> replace_with = input(f'Enter the letters to replace with: ')

There's no need for the f prefix.

> change_this_list = list(change_this)
> replace_with_list = list(replace_with)
>
> while True:
>     try:
>         for element in word_list:
>             for x in change_this_list:
>                 if element == x:
>                     to = word_list.index(element)
>                     replace = change_this_list.index(x)
>                     word_list[to] = replace_with_list[replace]
>         new_word = ''.join(word_list)
>         print(f'{new_word}')

The f-string is overkill. You might as well just have:

         print(new_word)

>         break
>     except:

Avoid a 'bare' except unless you _really_ mean it, which is virtually never. Catch only those exceptions that you're going to handle.

>         print(f'nope')


You can make it a lot shorter and faster by using a dict. The entire while loop section can be replaced with:

replacements = dict(zip(change_this, replace_with))
new_word = ''.join(replacements.get(letter, letter) for letter in word)
print(new_word)
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to