简体   繁体   English

如何精确比较字符串

[英]How to compare strings exactly

I want to compare 2 strings with each other. 我想相互比较2个字符串。

I tried 'in' , '==' and 'is' operator. 我尝试了'in''==''is'运算符。 But it is not working properly. 但是它不能正常工作。

1st code: 第一个代码:

myStrings = ['test1', 'test2', 'test3', 'test11', 'test111', 'test56']

for elem in myStrings:
    if 'test1' in elem:
        print('success')

2nd Code: 第二个代码:

myStrings = ['test1', 'test2', 'test3', 'test11', 'test12', 'test56']

for elem in myStrings:
    if 'test1' is elem[0:len('test1')]:
        print('success')

Expected: success should be printed only once. 预期: 成功应该只打印一次。 But it is printing 3 times. 但是它正在打印3次。 It is comparing successfully with 'test11' and 'test12' also. 它也成功地与'test11''test12'进行了比较。

Sorry, I did not explain the question completely. 抱歉,我没有完全解释这个问题。

The length of strings in the list is not fixed. 列表中字符串的长度不是固定的。 It is variable. 它是可变的。 And string 'test1' is substring for multiple strings. 字符串“ test1”是多个字符串的子字符串。

Now, in next step I also want to compare 'test11' to elements of the list. 现在,在下一步中,我还想将“ test11”与列表中的元素进行比较。 But here it is failing. 但是这里失败了。 Since it is matching to 'test11' and 'test111'. 由于它与“ test11”和“ test111”匹配。

Sorry for the language. 语言很抱歉。

Use == instead of is. 使用==代替is。

Difference between == and is operator in Python. Python中==和is运算符之间的区别。 The == operator compares the values of both the operands and checks for value equality. ==运算符比较两个操作数的值并检查值是否相等。 Whereas is operator checks whether both the operands refer to the same object or not. 而is运算符则检查两个操作数是否引用相同的对象。

A stackoverflow post about it: Is there a difference between "==" and "is"? 关于它的stackoverflow帖子: “ ==”和“ is”之间有区别吗?

myStrings = ['test1', 'test2', 'test3', 'test11', 'test12', 'test56']

for elem in myStrings:
    if 'test1' == elem:
        print('success')

output: 输出:

success

Try checking whether the element of the list is equivalent to 'test' : 尝试检查列表中的元素是否等效于'test'

myStrings = ['test1', 'test2', 'test3', 'test11', 'test12', 'test56']
for elem in myStrings:
   if elem=='test1':
     print('success')

OUTPUT : 输出

success

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM