Manos Stg
Manos Stg

Reputation: 84

My string letter replacement code doesn't work

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

I'm trying to make a Greeklish to Greek translator and it just seems I messed up.


input: "as"

output: "aςs"

what I want: "ας"


input: "sa"

output: "sa"

what I want: "σα"


input: "sakas"

output: "σakaςs"

what I want: "σαkας"

Upvotes: 2

Views: 72

Answers (2)

Asad Hussain
Asad Hussain

Reputation: 229

If you wanna understand the logic behind, the following code will help you understand how does it works.

def translate(text):
# checks 's' is present in 'text'
if 's' in text:
    # checks if 's' appears at the end of 'text'
    if text[-1] == 's':
        # checks if 's' appears between 'tex'
        if 's' in text[:-1]:
            text = text.replace('s', 'σ')

        # replace 's' with 'ς'
        text = text[:-1] + 'ς'
    else:
        # replace 's' with 'σ'
        text = text.replace('s', 'σ')

# checks 'a' is present in 'text'
if 'a' in text:
    # replace 'a' with 'α'
    text = text.replace('a', 'α')

return text

Upvotes: -1

Henry
Henry

Reputation: 3942

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.

Upvotes: 2

Related Questions