Python Forum
help with replacing charactersdef fix(block): alf = ['a', 'b', 'c', ' in a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help with replacing charactersdef fix(block): alf = ['a', 'b', 'c', ' in a string
#3
Here are the issues in your code:
  1. You always replace in the same block - overwriting get with the latest replacement operation result
  2. You don't check crossing list boundaries
  3. Remember p.1? It does not matter, because you exit after first iteration!
  4. You may end up replacing character many times - if you replace 'a' with 'c', then you'll replace 'c' with 'e', etc
  5. There are better ways to manage loop!
  6. There is module string that contains ascii_lowercase constant - well, that you may not have known
  7. Variable names - well, they are not very successful
Since you have shown some effort - here is the proper way to do it (I hope it is not homework)
from string import ascii_lowercase
def fix(word, char_offset=2):
    new_word = ''
    for char_ in word:
        # Get index of replacement character and keep it below 26, so for "z" it will be "b"
        char_index = ascii_lowercase.find(char_)
        if char_index > -1:
            replacement_index =  (char_index + char_offset) % 26
            new_word += ascii_lowercase[replacement_index]
         else:
            new_word += char_
    return new_word
PS I did not test the code - if there are some glitches, I leave fixing them to you as an excercise
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Messages In This Thread
RE: help with replacing charactersdef fix(block): alf = ['a', 'b', 'c', ' in a string - by volcano63 - Apr-18-2017, 07:14 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Replacing String Variable with a new String Name kevv11 2 840 Jul-29-2023, 12:03 PM
Last Post: snippsat
  Replacing a words' letters in a string cananb 2 3,533 Dec-01-2020, 06:33 PM
Last Post: perfringo
  Replacing characters in a string with a list cjms981 1 1,851 Dec-30-2019, 10:50 PM
Last Post: micseydel
  Replacing all letters in a string apart from the first letter in each word Carbonix 9 5,044 Jan-17-2019, 09:29 AM
Last Post: buran
  Replacing letters on a string via location Owenix 2 2,520 Sep-16-2018, 10:59 AM
Last Post: gruntfutuk
  Replacing variable in a split string and write new file python MyCode 1 3,591 Oct-30-2017, 05:20 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020