Pancir
Pancir

Reputation: 13

Python cyrillic to latinic converter

So recently I started learning Python. I made dictionary looking like this

a = input("Your Text Here: ")
dictt = {'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d',
     'ђ':'đ', 'е':'e', 'ж':'ž', 'з':'z', 'и':'i',
     'ј':'j', 'к':'k', 'л':'l', 'љ':'q', 'м':'m',
     'н':'n', 'њ':'w', 'о':'o', 'п':'p', 'р':'r',
     'с':'s', 'т':'t', 'ћ':'ć', 'у':'u', 'ф':'f',
     'х':'h', 'ц':'c', 'џ':'y', 'ш':'š'}

I want using for loop to change every cyrillic character to latinic and print it

Upvotes: 1

Views: 708

Answers (2)

Thierry Lathuille
Thierry Lathuille

Reputation: 24280

You can use the translate method of the string, that will translate your string according to a translation table.

You can build this table from your dict with str.maketrans.

So, that would be:

dictt = {'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d',
     'ђ':'đ', 'е':'e', 'ж':'ž', 'з':'z', 'и':'i',
     'ј':'j', 'к':'k', 'л':'l', 'љ':'q', 'м':'m',
     'н':'n', 'њ':'w', 'о':'o', 'п':'p', 'р':'r',
     'с':'s', 'т':'t', 'ћ':'ć', 'у':'u', 'ф':'f',
     'х':'h', 'ц':'c', 'џ':'y', 'ш':'š'}

table  = str.maketrans(dictt)

a = "привет"
print(a.translate(table))
# privet

Note that you can invoke maketrans in a different way, with two strings of same length, with the corresponding characters in the same order:

table  = str.maketrans('абвгд', 'abvgd')

print("баг".translate(table))
# bag

If you really want to use a for loop, note that you should avoid appending characters one by one to a string, this is very inefficient in Python. The efficient way is to append the characters to a list, then join them by an empty string:

def translate(text):
    out = ''.join([dictt[char] for char in text])
    for char in text:
        out.append(dictt[char])
    return ''.join(out)

print(translate("привет"))
# privet

You can rewrite that in a more compact way using a list comprehension:

def translate(text):
    return ''.join([dictt[char] for char in text])

Upvotes: 2

Serhii Derevianko
Serhii Derevianko

Reputation: 163

a = input("Your Text Here: ")
dictt = {'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d',
     'ђ':'đ', 'е':'e', 'ж':'ž', 'з':'z', 'и':'i',
     'ј':'j', 'к':'k', 'л':'l', 'љ':'q', 'м':'m',
     'н':'n', 'њ':'w', 'о':'o', 'п':'p', 'р':'r',
     'с':'s', 'т':'t', 'ћ':'ć', 'у':'u', 'ф':'f',
     'х':'h', 'ц':'c', 'џ':'y', 'ш':'š', ' ':' '}
new_a = ''
for i in list(a):
    new_a += dictt.get(i.lower(), i)

print(new_a)

Upvotes: 1

Related Questions