2

i am trying to write a python program that prints music notes (like đť…ž -> u1d15e). However, i cant quite get it to work.

Here is what i get using the following code

note = '\U0001d15e'
bytes = note.encode('utf-8')
print(bytes)

>>> b'\xf0\x9d\x85\x9e'

If i try to print the string directly i get

note = '\U0001d15e'
# bytes = note.encode('utf-8')
print(note)

Traceback (most recent call last):
  File "c:\___\___\___\file.py", line 34, in <module>
    print(note)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\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 '\U0001d15e' in position 0: character maps to <undefined>

I am not sure what the problem is. I know that similar questions have been asked before, however the proposed solution did not work for me. Thank you for your help in advance :)

i am using python 3.10.4

3
  • When I run print(note) in IDLE I get a question mark which indicates that the font can't handle the code point, but I don't get any error. Commented Nov 24, 2022 at 15:00
  • The short version is that this is a Windows problem (more specifically, a cmd.exe problem) that doesn't really have anything to do with Python, and you may or may not be able to do anything about it, depending on the character. Commented Nov 24, 2022 at 15:06
  • Thank you for the answer, the problem was my windows console was not set to utf-8 Commented Nov 24, 2022 at 21:58

1 Answer 1

1

My system doesn't like that representation either, but can directly put it into a string and print() it

To me, this is some artifact of your system being Windows and you need to set your console to use UTF-8 instead of cp1252

Using UTF-8 Encoding (CHCP 65001) in Command Prompt / Windows Powershell (Windows 10)

>>> "đť…ž" == "\U0001d15e"
True
>>> note = "đť…ž"
>>> note.encode()
b'\xf0\x9d\x85\x9e'
>>> print(note)
đť…ž
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the reply. i changed my windows console to utf-8, now it works!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.