简体   繁体   English

如何在 python 中按字母顺序对字符串进行排序

[英]How can i sort a string in alphabetical order in python

I've been trying to sort a string in alphabetical order and got stuck.我一直在尝试按字母顺序对字符串进行排序并且卡住了。 I know that the sort function exists on python but i cant use it.我知道 python 上存在排序 function 但我不能使用它。 Cant even use the.join method as well.甚至不能使用 .join 方法。 Gotta do it all using for loops.必须使用 for 循环来完成这一切。

def wordOrder(word):
    word =  list(word)
    for i in range(0, len(word)):
        for j in range(i, len(word)):
            if word[i] > word[j]:
                word[i], word[j] = word[j], word[i]
    word = ""+ str(word)
    return word

Here's what i have but I did it with a tutor and cant remember what the if section does.这是我所拥有的,但我是和导师一起做的,不记得 if 部分做了什么。 Thank you!谢谢!

You can use ( >, <, <=, <=, ==, .= ) to compare two strings.您可以使用(>、<、<=、<=、==、.=)来比较两个字符串。 Python compares string lexicographically ie using ASCII value of the characters. Python 按字典顺序比较字符串,即使用字符的 ASCII 值。

If statement compares the first and second letter's ASCII value. If 语句比较第一个和第二个字母的 ASCII 值。 if its greater than exchange.如果它大于交换。

for example,例如,

print(wordOrder('ba'))

output
['a', 'b']

ASCII value of small a is 97 and b is 98 .a的 ASCII 值是97b98

if word[i] > word[j]:
                word[i], word[j] = word[j], word[i]

So,所以,

 word[i] --> b --> 98
 word[j]  --> a --> 97

Since, 98 is greater than 97 we swap both the values.因为 98 大于 97,所以我们交换两个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM