Python字符串比较

Python | 字符串比较 (Python | String comparison)

In python programming language, strings can be compared using the relationship/ comparisons operators like ==, !=, <, >, <=, >=.

在python编程语言中,可以使用诸如== , != , < , > , <= , > =之类的关系/比较运算符来比较字符串。

These operators need two operands (strings), checks the characters (based on its UNICODE values) of the string and return True or False.

这些运算符需要两个操作数(字符串),检查字符串的字符(基于其UNICODE值)并返回True或False 。

Example 1:

范例1:

str1 = 'IncludeHelp'

# comparison
print("str1 == \'IncludeHelp\'): ", str1 == 'IncludeHelp')
print("str1 != \'IncludeHelp\'): ", str1 != 'IncludeHelp')
print("str1 <  \'IncludeHelp\'): ", str1 <  'IncludeHelp')
print("str1 <= \'IncludeHelp\'): ", str1 <= 'IncludeHelp')
print("str1 >  \'IncludeHelp\'): ", str1 >  'IncludeHelp')
print("str1 >= \'IncludeHelp\'): ", str1 >= 'IncludeHelp')

Output

输出量

str1 == 'IncludeHelp'):  True
str1 != 'IncludeHelp'):  False
str1 <  'IncludeHelp'):  False
str1 <= 'IncludeHelp'):  True
str1 >  'IncludeHelp'):  False
str1 >= 'IncludeHelp'):  True

Example 2:

范例2:

str1 = 'IncludeHelp'
str2 = 'includehelp'

# comparison
print("str1 == str2: ", str1 == str2)
print("str1 != str2: ", str1 != str2)
print("str1 <  str2: ", str1 <  str2)
print("str1 <= str2: ", str1 <= str2)
print("str1 >  str2: ", str1 >  str2)
print("str1 >= str2: ", str1 >= str2)

Output

输出量

str1 == str2:  False
str1 != str2:  True
str1 <  str2:  True
str1 <= str2:  True
str1 >  str2:  False
str1 >= str2:  False

Example 3:

范例3:

str1 = 'IncludeHelp'
str2 = 'includehelp'
str3 = 'IncludeHelp'

if str1 == str2:
  print(str1, "is equal to", str2)
else:  
  print(str1, "is not equal to", str2)

if str3 == str3:
  print(str3, "is equal to", str3)
else:  
  print(str3, "is not equal to", str3)

Output

输出量

IncludeHelp is not equal to includehelp
IncludeHelp is equal to IncludeHelp

Example 4:

范例4:

# input two strings
str1 = input("Enter string 1: ")
str2 = input("Enter string 2: ")

# comparing
if str1 < str2:
  print(str1, "comes before", str2)
elif str1 > str2:
  print(str1, "comes after", str2)  
else:
  print(str1, "and", str2, "are same")

Output

输出量

RUN 1:
Enter string 1: Honda Amaze
Enter string 2: Honda City
Honda Amaze comes before Honda City

RUN 2:
Enter string 1: BMW
Enter string 2: Audi
BMW comes after Audi

RUN 3:
Enter string 1: BMW z4
Enter string 2: BMW z4
BMW z4 and BMW z4 are same


翻译自: https://www.includehelp.com/python/string-comparison.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值