# 定义一个包含多个字符的字符串
my_string = "Hello, world!"
# 使用字符串方法来检查字符串中是否包含子字符串
if "world" in my_string:
print("The string contains 'world'.")
else:
print("The string does not contain 'world'.")
这段代码定义了一个包含多个字符的字符串 my_string,然后使用字符串方法 in 来检查字符串中是否包含子字符串 "world"。如果字符串包含 "world",则代码将打印 "The string contains 'world'.";否则,代码将打印 "The string does not contain 'world'."。在这个示例中,字符串中包含 "world",因此代码将打印 "The string contains 'world'."。
你也可以使用其他字符串方法,如 find() 或 index() 来查找字符串中的子字符串。例如,下面的代码使用 find() 方法来查找子字符串 "world":
# 定义一个包含多个字符的字符串
my_string = "Hello, world!"
# 使用字符串方法 find() 来查找子字符串
if my_string.find("world") != -1:
print("The string contains 'world'.")
else:
print("The string does not contain 'world'.")
这段代码与之前的代码类似,但使用了 find() 方法来查找子字符串 "world"。如果字符串包含 "world",则 find() 方法将返回子字符串在字符串中的索引位置(从0开始),否则将返回-1。因此,代码使用条件语句来检查 find() 方法返回的值是否为-1。如果不是,则字符串包含子字符串 "world",代码将打印 "The string contains 'world'.";否则,代码将打印 "The string does not contain 'world'."。在这个示例中,字符串中包含 "world",因此代码将打印 "The string contains 'world'."。