以下是一个保留包含子字符串的字符串的代码示例:
def keep_substring(strings, substring):
result = []
for string in strings:
if substring in string:
result.append(string)
return result
strings = ["hello", "world", "hi", "how are you"]
substring = "o"
result = keep_substring(strings, substring)
print(result) # 输出: ['hello', 'world', 'how are you']
以上代码中,keep_substring
函数接受一个字符串列表和一个子字符串作为参数。它遍历列表中的每个字符串,如果子字符串在当前字符串中出现,就将该字符串添加到结果列表中。最后,返回结果列表。
在示例中,输入的字符串列表是["hello", "world", "hi", "how are you"]
,子字符串是"o"
。执行keep_substring
函数后,返回的结果是['hello', 'world', 'how are you']
,这是因为这些字符串中都包含子字符串"o"
。
你可以根据自己的需求修改和扩展这个示例代码。