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
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.