Character Convertor

Viewed 94
turk = {"Ç":"C","ç":"c","Ğ":"G","ğ":"g","İ":"I","ı":"i",
        "Ö":"O","ö":"o","Ş":"S","ş":"s","Ü":"U","ü":"u"}

eng = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz \t1234567890"

space = " "

word = input("Enter a word")


def turkChar (word):
    newword = ""
    for c in word:
        if c in eng:
            newword = newword + c
        elif c in turk:
            newword = newword + turk[c]
        else:
            newword = newword + space
    return newword
       

I wrote this simple code which turns Turkish chars into English. I added space variable to make a space but what if user wants to make more space or tab or even numbers. How can I make this ?

3 Answers

Python has a string function called translate() that is made for this and is very efficient (much more efficient than a loop/dict-lookup). You can make a translation table with a dictionary exactly like the one you already have, which you can create with maketrans() then pass to translate():

turk = str.maketrans({"Ç":"C","ç":"c","Ğ":"G","ğ":"g","İ":"I","ı":"i",
        "Ö":"O","ö":"o","Ş":"S","ş":"s","Ü":"U","ü":"u"})

s = "Hellö ĞÇ 123"

s.translate(turk)
# 'Hello GC 123'

I think you should have a single map from Turkish to English. So A would map to A, B to B and so on, in addition to the turk dictionary you already have. You can then add the space, tab and any other character to the mapping.

Your code becomes a loop with a dictionary lookup using the get function.

I don't think you should treat the space, tab and number characters any differently than your eng characters. I would simply extend your characters like this:

eng = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz \t1234567890"

Then we can remove the 'space' parts, ending up with this:

turk = {"Ç":"C","ç":"c","Ğ":"G","ğ":"g","İ":"I","ı":"i",
        "Ö":"O","ö":"o","Ş":"S","ş":"s","Ü":"U","ü":"u"}

eng = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz \t1234567890"

word = input("Enter a word")

def turkChar(word, turk):
    newword = ""
    for c in word:
        if c in eng:
            newword = newword + c
        elif c in turk:
            newword = newword + turk[c]
    return newword
  • A tab character is written as \t in a string.
  • Noticed you had a missing lower h in your eng string.
  • You defined turk as an argument but not eng, either define both or neither.
  • If character isn't found in eng nor turk then it's ignored.
Related