Python 中字符串的逻辑运算符?
Python 逻辑运算符“and”和“or”可应用于字符串。空字符串返回 False 的布尔值。我们首先了解这两种逻辑运算符“and”和“or”的行为。
And 运算符
如果有任何 falsey 值,则返回第一个 falsey 值,否则返回表达式或运算符中的最后一个值:返回第一个 truthly 值(如果有的话),否则返回表达式中的最后一个值。
| 操作 | 结果 |
|---|---|
| X and y | 如果 x 为 false,则为 y,否则为 x |
| X and y | 如果 x 为 false,则为 x,否则为 y |
| Not x | 如果 x 为 false,则为 true,否则为 false |
以下是展示在 python 中字符串上使用逻辑运算符的程序 −
str1 = ""
str2 = "python"
print(repr(str1 and str2))
print(repr(str2 and str1))
print(repr(str1 or str2))
print(repr(str2 or str1))
str1 = "Hello "
print(repr(str1 and str2))
print(repr(str2 and str1))
print(repr(str1 or str2))
print(repr(str2 or str1))
print(repr(not str1))
str2 = ""
print(repr(not str2))
str2 = "hello"
print("Hello == hello: ", str1 == str2)输出
'' '' 'python' 'python' 'python' 'Hello ' 'Hello ' 'python' False True Hello == hello: False
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP