gpt4 book ai didi

python - 按顺序打印字符串

转载 作者:行者123 更新时间:2023-11-28 20:33:06 25 4
gpt4 key购买 nike

目标是从用户那里读取一个字符串,并在不使用列表或 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com