【发布时间】:2021-11-25 20:58:37
【问题描述】:
我正在尝试创建一个程序,该程序可以获取字符串并返回按其 ASCII 值排序的字符的字符串(例如:“Hello, World!”应该返回“!,HWdellloor”)。
我试过了,效果很好:
text = "Hello, World!"
cop = []
for i in range(len(text)):
cop.append(ord(text[i]))
cop.sort()
ascii_text = " ".join([str(chr(item)).strip() for item in cop])
print(ascii_text)
但我很想知道仅使用字符串操作函数是否可以实现这样的事情。
【问题讨论】:
-
为什么?为什么不直接排序字符?此外,在 Python 3 中,字符串是 Unicode 而不是 ASCII。
-
''.join(sorted(text))。字符串是一个序列。调用ord()是不必要的(它不会改变转换为整数的排序顺序)。 -
@PanagiotisKanavos 确实,但我希望根据 ascii 值进行排序
-
@DietrichEpp 谢谢,现在我觉得自己很愚蠢,但至少它起作用了 xd
-
旁注:更容易创建
cop:cop = [ord(c) for c in text]。另外,str(chr())是多余的。
标签: python python-3.x string ascii