Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My string letter replacement code doesn't work [python]

import re
text = input("Enter text: ")
text = text.lower()
len = len(text)
lenid = len - 1

def translate(text):
    translation = ""
    slocid = text.index("s")
    for letter in text:
        if (text[lenid] == "s") or (text[slocid + 1] == " "):
          translation = re.sub(r"s\b", lambda m: m.group().replace("s", "ς"), text)
        if letter == "s":
          translation = translation.replace("s", "σ")
        if letter == "a":
            translation = translation + "α"
        else:
            translation = translation + letter
    return translation

print(translate(text))

I want to make a program where, when i enter a text, i get back the same text but all the "s"s are replaced with "ς" if the "s"s are at the end of a word, if they’re not at the end of the word, i want them to be replaced with "σ". If the letter is "a" i want it replaced with "α". I’m trying to make a greeklish to greek translator and it just seems i messed up.


input: as

output: aςs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

what i want: ας


input: sa

output: sa

what i want: σα


input: sakas

output: σakaςs

what i want: σαkας

>Solution :

You currently translate the text character by character, but your regex and replace work on the whole string so you can just apply them to the whole string instead.

def translate(text):
    return re.sub(r"s\b", "ς", text)\
           .replace("s", "σ")\
           .replace("a", "α")

This will first sub your regex to replace ending ‘s’ characters, then replaces the remaining ‘s’ characters and then the ‘a’ characters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading