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 in
the keyword to determine string2
whether exists string1
in . If present, the condition is true and output {string2} 存在于 {string1} 中
. Otherwise, the condition is false and output {string2} 不存在于 {string1} 中
.
Note that in
keywords 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 string1
and string2
to lowercase before comparing. This way, case-insensitive string comparisons will yield correct results.