Python检查字符串是否包含另一个字符串

String manipulation is a common task in any programming language. Python provides two common ways to check if a string contains another string.

字符串操作是任何编程语言中的常见任务。 Python提供了两种常用方法来检查一个字符串是否包含另一个字符串。

Python检查字符串是否包含另一个字符串 (Python check if string contains another string)

Python string supports in operator. So we can use it to check if a string is part of another string or not. The in operator syntax is:

Python字符串支持in运算符。 因此,我们可以使用它来检查一个字符串是否是另一个字符串的一部分。 in运算符的语法为:

sub in str

It returns True if “sub” string is part of “str”, otherwise it returns False.

它返回True ,如果“子”字符串为“海峡”的一部分,否则返回False

Let’s look at some examples of using in operator in Python.

让我们看一些在Python中使用in运算符的示例。

str1 = 'I love Python Programming'

str2 = 'Python'

str3 = 'Java'

print(f'"{str1}" contains "{str2}" = {str2 in str1}')
print(f'"{str1}" contains "{str2.lower()}" = {str2.lower() in str1}')
print(f'"{str1}" contains "{str3}" = {str3 in str1}')

if str2 in str1:
    print(f'"{str1}" contains "{str2}"')
else:
    print(f'"{str1}" does not contain "{str2}"')

Output:

输出:

"I love Python Programming" contains "Python" = True
"I love Python Programming" contains "python" = False
"I love Python Programming" contains "Java" = False
"I love Python Programming" contains "Python"

When we use in operator, internally it calls __contains__() function. We can use this function directly too, however it’s recommended to use in operator for readability purposes.

当我们在运算符中使用时,在内部它会调用__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

使用find()检查一个字符串是否包含另一个子字符串 (Using find() to check if a string contains another substring)

We can also use string find() function to check if string contains a substring or not. This function returns the first index position where substring is found, else returns -1.

我们还可以使用string find()函数来检查string是否包含子字符串。 此函数返回找到子字符串的第一个索引位置,否则返回-1。

str1 = 'I love Python Programming'

str2 = 'Python'

str3 = 'Java'

index = str1.find(str2)
if index != -1:
    print(f'"{str1}" contains "{str2}"')
else:
    print(f'"{str1}" does not contain "{str2}"')

index = str1.find(str3)
if index != -1:
    print(f'"{str1}" contains "{str3}"')
else:
    print(f'"{str1}" does not contain "{str3}"')

Output:

输出:

"I love Python Programming" contains "Python"
"I love Python Programming" does not contain "Java"
GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

翻译自: https://www.journaldev.com/23795/python-check-if-string-contains-another-string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值