更新时间:2023-11-28 19:56:40
信不信由你,所有字符都已经隐式分配了一个数字:它们的 ASCII 字符代码.您可以使用 ord()
函数访问它们,或者直接比较它们:
但请注意,大写字母编码为 65 - 90,而小写字母编码为 97 - 122,因此:
>>>C">乙"错误的您必须确保比较所有大写字母或所有小写字母.
这是一个可能的函数,它使用上述信息来检查给定的字符串是否按字母顺序排列,只是为了让您开始:
def isAlphabetical(word):对于 xrange(len(word) - 1) 中的 i:如果单词[i] >字[i+1]:返回错误返回真
I have a text file full of words. I need to go through the text file and count the number of words that are spelled in alphabetical order. I am struggling to think of way to figure out if a word is in alphabetical order.
I have already looked around and have seen that it can be done with sorted. However, we haven't yet learned about sort in class so I can't use it. Help/tips much appreciated.
Do I need to do something like assigning each letter of the alphabet a number?
Believe it or not, all characters are already implicitly assigned a number: their ASCII character codes. You can access them by using the ord()
function, or compare them directly:
>>> "a" > "b"
False
>>> "b" > "a"
True
Beware though, capital letters are coded 65 - 90, while lowercase letters are coded 97 - 122, so:
>>> "C" > "b"
False
You have to ensure that you are comparing all uppercase or all lowercase letters.
Here's one possible function that uses the above information to check if a given string is in alphabetical order, just to get you started:
def isAlphabetical(word):
for i in xrange(len(word) - 1):
if word[i] > word[i+1]:
return False
return True