【问题标题】:How to compare strings exactly如何准确比较字符串
【发布时间】:2019-05-20 11:52:45
【问题描述】:

我想比较两个字符串。

我尝试了'in''==''is' 运算符。但它不能正常工作。

第一个代码:

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

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

第二个代码:

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

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

预期: success 应该只打印一次。但它打印了3次。它也与'test11''test12' 成功比较。

对不起,我没有完全解释这个问题。

列表中字符串的长度不固定。它是可变的。 并且字符串 'test1' 是多个字符串的子字符串。

现在,在下一步中,我还想将“test11”与列表中的元素进行比较。但在这里它失败了。因为它匹配 'test11' 和 'test111'。

对不起语言。

【问题讨论】:

标签: python python-3.x string substring


【解决方案1】:

使用 == 代替 is。

Python 中 == 和 is 运算符的区别。 == 运算符比较两个操作数的值并检查值是否相等。而 is 运算符检查两个操作数是否引用同一个对象。

关于它的 stackoverflow 帖子: Is there a difference between "==" and "is"?

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

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

输出:

success

【讨论】:

    【解决方案2】:

    尝试检查列表的元素是否等于'test'

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

    输出

    success
    

    【讨论】:

      猜你喜欢
      • 2016-05-18
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多