p ython判断字符串相等
时间: 2024-01-02 11:02:35 浏览: 33
在Python中,可以使用 `==` 运算符来判断两个字符串是否相等。例如:
```python
str1 = "hello"
str2 = "world"
str3 = "hello"
if str1 == str2:
print("str1 is equal to str2")
else:
print("str1 is not equal to str2")
if str1 == str3:
print("str1 is equal to str3")
else:
print("str1 is not equal to str3")
```
输出结果为:
```
str1 is not equal to str2
str1 is equal to str3
```
注意,字符串比较是区分大小写的,也就是说,"Hello" 和 "hello" 是不相等的。如果你想进行不区分大小写的字符串比较,可以先将字符串转换为小写或大写再进行比较。例如:
```python
str1 = "Hello"
str2 = "hello"
if str1.lower() == str2.lower():
print("str1 is equal to str2 (case insensitive)")
else:
print("str1 is not equal to str2 (case insensitive)")
```
输出结果为:
```
str1 is equal to str2 (case insensitive)
```