Python字符串包含

Python String class has __contains__() function that we can use to check if it contains another string or not.

Python字符串类具有__contains__()函数,我们可以使用该函数检查它是否包含另一个字符串。

Python字符串包含 (Python String contains)

Python string __contains__() is an instance method and returns boolean value True or False depending on whether the string object contains the specified string object or not. Note that the Python string contains() method is case sensitive.

Python字符串 __contains__()是一个实例方法,根据字符串对象是否包含指定的字符串对象,返回布尔值True或False。 请注意,Python字符串contains()方法区分大小写。

Let’s look at a simple example for string __contains__() method.

我们来看一个简单的字符串__contains __()方法示例。

s = 'abc'

print('s contains a =', s.__contains__('a'))
print('s contains A =', s.__contains__('A'))
print('s contains X =', s.__contains__('X'))

Output:

输出:

s contains a = True
s contains A = False
s contains X = False

We can use __contains__() function as str class method too.

我们也可以使用__contains __()函数作为str类方法。

print(str.__contains__('ABC', 'A'))
print(str.__contains__('ABC', 'D'))

Output:

输出:

True
False

Let’s look at another example where we will ask the user to enter both the strings and check if the first string contains the second string or not.

让我们看另一个示例,在该示例中,我们将要求用户输入两个字符串,并检查第一个字符串是否包含第二个字符串。

input_str1 = input('Please enter first input string\n')

input_str2 = input('Please enter second input string\n')

print('First Input String Contains Second String? ', input_str1.__contains__(input_str2))

Output:
Please enter first input string
JournalDev is Nice
Please enter second input string
Dev
First Input String Contains Second String? True

输出:
请输入第一个输入字符串
JournalDev很不错
请输入第二个输入字符串
开发人员
第一个输入字符串包含第二个字符串? 真正

GitHub Repository. GitHub存储库中签出更多Python字符串示例。

翻译自: https://www.journaldev.com/23451/python-string-contains

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值