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. Cant even use the.join method as well. Gotta do it all using for loops.
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. Thank you!
You can use ( >, <, <=, <=, ==, .= ) to compare two strings. Python compares string lexicographically ie using ASCII value of the characters.
If statement compares the first and second letter's ASCII value. if its greater than exchange.
for example,
print(wordOrder('ba'))
output
['a', 'b']
ASCII value of small a
is 97
and b
is 98
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.