0

I want to replace the character ي (Unicode:\u064A) With the character ی (Unicode:\u06CC). I tried the following code:

import unicodedata as ud
normalForm = ud.normalize('NFKD','رزاﻗﻲ')
for charr in normalForm:
  if charr == 'ي':
    print('true')
    charr = charr.replace('ي','ی')
print(normalForm)

However, this code doesn't work, and it returns the same character:

رزاقي

while it should return:

رزاقی

I wanted to try replacing using their Unicode (or any other method), How can I achieve this?

4
  • 2
    normalForm = normalForm.replace(…). You need to call replace on the whole string and reassign it, not just a single character. Commented Sep 1, 2021 at 6:38
  • 2
    charr = charr.replace('ي','ی') doesn't impact the original string, because charr is a separate string object that exists independently of the normalForm. That said, .replace is designed to operate on entire strings already. Remember, Python doesn't have a separate type for individual characters. It just makes separate length-1 strings. Commented Sep 1, 2021 at 6:40
  • @KarlKnechtel Oh yes (facepalm) Thanks! Commented Sep 1, 2021 at 6:42
  • Even if you did have to iterate, you would want to create a new string rather than modifying the original, possibly by using a comprehension. Commented Sep 1, 2021 at 6:45

1 Answer 1

1

Call .replace directly on the string. Python string are immutable, so you have to assign the return value to retain the change as well:

import unicodedata as ud

original = 'رزاﻗﻲ'
nfkd = ud.normalize('NFKD',original)
replaced = nfkd.replace('ي','ی')
print('orig',ascii(original),original)
print('nfkd',ascii(nfkd),nfkd)
print('repl',ascii(replaced),replaced)

Output with ASCII representation since visually they look the same:

orig '\u0631\u0632\u0627\ufed7\ufef2' رزاﻗﻲ
nfkd '\u0631\u0632\u0627\u0642\u064a' رزاقي
repl '\u0631\u0632\u0627\u0642\u06cc' رزاقی
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.