在 Python 中,可以使用多种方法判断字符串变量是否等于指定的字符串。

1. 比较运算符 ==

可以使用 == 运算符来比较两个字符串是否相等。例如:

s1 = 'hello'
s2 = 'world'
if s1 == 'hello':
    print('s1 is equal to 'hello'')

2. equals() 方法

字符串对象还提供了一个 equals() 方法来判断两个字符串是否相等。例如:

s3 = 'Python'
s4 = 'python'
if s3.equals(s4):
    print('s3 is equal to s4')
else:
    print('s3 is not equal to s4')

注意:

  • Python 中字符串的比较运算符区分大小写。
  • equals() 方法也区分大小写。

忽略大小写比较

如果需要忽略大小写比较,可以使用 lower()upper() 方法将字符串转换成小写或大写,然后再进行比较。例如:

s5 = 'Hello'
s6 = 'hello'
if s5.lower() == s6.lower():
    print('s5 is equal to s6 (ignoring case)')

通过以上方法,您可以轻松地判断 Python 中字符串变量是否等于指定的字符串。

Python 字符串比较:判断字符串是否相等

原文地址: https://www.cveoy.top/t/topic/oq4c 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录