You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串转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) for ord(c): ord() returns the integer Unicode code point for a given character (e.g., ord('A') gives 65, ord('😀') gives 128512).
  • Used an f-string in the print statement for cleaner, more readable formatting.
  • Removed unnecessary line breaks in the input prompt 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:03:50