关系运算符对于字符串来说也可用。比如可以看看两个字符串是不是相等:
$ cat c.py
#!/bin/python
word = 'banana'
if word == 'banana':
print('all ringt, bananas')
$ python3 c.py
all ringt, bananas
其他的关系运算符> <可以按照ASCII值的大小来比较字符串的大小:
$ cat c.py
word = 'jack' #定义word为jack
if word < 'banana':
print('your word, ' + word + ', comes before banana.')
elif word > 'banana':
print('Your word, ' + word + ', comes after banana.')
else:
print('All right, bananas.')
$ python3 c.py
Your word, jack, comes after banana.
$ cat c.py
#!/bin/python
word = 'app' #定义word为app
if word < 'banana':
print('your word, ' + word + ', comes before banana.')
elif word > 'banana':
print('Your word, ' + word + ', comes after banana.')
else:
print('All right, bananas.')
$ python3 c.py
your word, app, comes before banana.
ASCII码顺序的比较规则是,从第一个字符开始,顺次向后直到出现不同的字符为止,然后以第一个不同的字符的ASCII值确定。
例如上面的"jack"和"banana",第一个字母就不相同,j的ASCII值比b的ASCII值大,所以这二个字符串的比较结果是"jack" > "banana"。所以打印Your word, jack, comes after banana.
"app"与"banana"比较,a的ASCII值比b的ASCII值大,所以字符串"app" > "banana"。所以打印your word, app, comes before banana.
结束。