Home > Back-end >  How to use Special characters in pyton?
How to use Special characters in pyton?

Time:11-28

this is my code

f = open('test.txt','w')

f.write("\N{Circled White Star}")
f.close

And I get this error

Traceback (most recent call last):
  File "f:/mc experiment/python/SkyblockSniper-main/df.py", line 3, in <module>
    f.write("\N{Circled White Star}")
  File "F:\programing\python\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u272a' in position 0: character maps to <undefined>

What I expected

The test.txt file should have

What i got

<nothing>

please help

CodePudding user response:

Try changing the encoding of the file you open. UTF-8 worked for my testing. You should also open files using context managers instead of the way you did it.

star = "✪"
with open('test.txt', 'w', encoding="UTF-8") as f:
    f.write(f"\n{star}")

CodePudding user response:

Without access to the original Circled White Star symbol, unicode may be useful

star = '\u272A'
    with open('test.txt', 'w', encoding="UTF-8") as f:
    f.write(star)
  • Related