在Python3中,比较字符串通常有以下几种方法:
1. 使用 `==` 运算符比较两个字符串是否完全相同。
str1 = "abc"
str2 = "abc"
print(str1 == str2) 输出:True
2. 使用 `is` 运算符比较两个字符串是否是同一个对象(即它们在内存中是否指向同一个位置)。
str1 = "abc"
str2 = "abc"
print(str1 is str2) 输出:True
3. 使用 `len()` 函数比较字符串的长度。
str1 = "abc"
str2 = "abcd"
print(len(str1) < len(str2)) 输出:True
4. 使用比较运算符 `>`、`<`、`>=`、`<=` 来比较字符串的大小。比较规则是从第一个字符开始比较,如果字符的ASCII值较大,则该字符串被认为较大。如果所有字符都相同,则较短的字符串被认为是较小的。
str1 = "abc"
str2 = "abcd"
print(str1 < str2) 输出:True
5. 使用内置函数 `ord()` 获取每个字符的Unicode编码,然后进行比较。
str1 = "abc"
str2 = "xyz"
print(ord(str1) > ord(str2)) 输出:True
请注意,Python3中已经移除了 `cmp()` 函数,因此不建议使用它进行字符串比较。