字符串转Unicode报错:name 'unicode' is not defined,求代码修复方案
Fixing the "name 'unicode' is not defined" Error in Your String-to-Unicode Program
Hey there! That error is popping up because you're working in Python 3, where the unicode() function from Python 2 no longer exists. In Python 3, all strings are Unicode by default—so you don’t need that function to convert characters to Unicode. Instead, if you want the numerical Unicode code point for each character, you’ll use the ord() function instead.
Here's your fixed code, with cleaner formatting and the necessary change:
inp = input("PLEASE ENTER A CHARACTER OR STRING: ") display = [c for c in inp] uni = [ord(c) for c in inp] # Replaced unicode() with ord() print(f"\nTHE CHARACTER(S) {display} ARE REPRESENTED IN UNICODE AS {uni}.")
What changed:
- Swapped
unicode(c)forord(c):ord()returns the integer Unicode code point for a given character (e.g.,ord('A')gives65,ord('😀')gives128512). - Used an f-string in the
printstatement for cleaner, more readable formatting. - Removed unnecessary line breaks in the
inputprompt to avoid odd spacing.
If you instead wanted the Unicode escape string representation (like \u0041 for 'A') instead of the numerical code, you could use this line instead:
uni = [c.encode('unicode-escape').decode() for c in inp]
That would give you outputs like ['\\u0041', '\\u0042'] for input "AB".
内容的提问来源于stack exchange,提问作者Ethan KAO
相关产品推荐
相关产品推荐

