Python determines whether a string is within another string

To determine if a string is within another string, you can use the keyword in Python in. Here is a sample code:

string1 = "Hello, World!"
string2 = "Hello"

if string2 in string1:
    print(f"{
      
      string2} 存在于 {
      
      string1} 中")
else:
    print(f"{
      
      string2} 不存在于 {
      
      string1} 中")

Output:

Hello 存在于 Hello, World! 中

In the above example, we use inthe keyword to determine string2whether exists string1in . If present, the condition is true and output {string2} 存在于 {string1} 中. Otherwise, the condition is false and output {string2} 不存在于 {string1} 中.

Note that inkeywords are case-sensitive. If you want to perform a case-insensitive string comparison, you can use the string's lower()or upper()method to convert the strings to the same case and then compare them. For example:

string1 = "Hello, World!"
string2 = "hello"

if string2.lower() in string1.lower():
    print(f"{
      
      string2} 存在于 {
      
      string1} 中")
else:
    print(f"{
      
      string2} 不存在于 {
      
      string1} 中")

Output:

hello 存在于 Hello, World! 中

In this example, we use lower()the method to convert string1and string2to lowercase before comparing. This way, case-insensitive string comparisons will yield correct results.

Guess you like

Origin blog.csdn.net/m0_66238629/article/details/131616579