如何精确比较字符串

2024-09-28 21:34:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想比较两个字符串。你知道吗

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

第1代码:

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”匹配。你知道吗

对不起,我的语言。你知道吗


Tags: 字符串代码inforifissuccesstest1
2条回答

使用==代替is。你知道吗

在Python中,==和之间的差异是运算符。==运算符比较两个操作数的值并检查值是否相等。而is运算符检查两个操作数是否引用同一对象。你知道吗

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

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

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

输出:

success

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

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

输出

success

相关问题 更多 >