python - 按顺序打印字符串

标签 python python-3.x

目标是从用户那里读取一个字符串,并在不使用列表或 sort() 的情况下将该字符串按 ASCII 代码的顺序排列下面是我的代码

answer = input("enter string: ")
len_ans = len(answer)
new_answer = ""
previous = " "
leftover =""

while True:
    for i in range(len_ans):

        if (ord(previous[0])) >= (ord(answer[i])):
            new_answer += previous
        else:
            leftover += previous
        print(new_answer)

        previous = answer[i]

    new_answer += leftover
    leftover = ""

    answer = new_answer

    if answer == new_answer:
        print(new_answer)
        break
    else: 
        new_answer = ""

最佳答案

使用sorted函数:

>>> s = 'Hello, world!'

>>> sorted(s)
=> [' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']   

>>> ''.join(sorted(s))
=> ' !,Hdellloorw'

关于python - 按顺序打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51241952/

相关文章:

python - Django 更新 Celery 异步任务中的设置

python - 将 <Python.h> 包含到 makefile.am

python - 如何在 ubuntu 中的 localhost 上运行简单的 cgi-bin python 网站

python - py3 中的 OpenCV Python : how to avoid cv2. imwrite() 内存 "leak"?

python - 提取带有可选结束模式的字符串

python - 使用Selenium截图时的"TypeError: get_screenshot_as_file() takes exactly 2 arguments (1 given)"

python - 关于创建 WMS 服务和桌面客户端的一些建议?

python - 使用 docker-compose up 运行时如何优雅地停止 Dockerized Python ROS2 节点?

python - Pandas 数据框,根据唯一值的数量选择 n 个随机行

python-3.x - 如何为 pkg-config 设置别名?