Python - 提取字符串直到其他字符串的所有字符出现
给定一个字符串,任务是编写一个Python程序来提取,直到找到其他字符串中的所有字符。
Input : test_str = “geeksforgeeks is best for all geeks”, check_str = “freak”
Output : geeksforgeeks is best for a
Explanation : a is last letter in freak to be present in string. The string is printed till first occurrence of a.
Input : test_str = “geeksforgeeks is best for all geeks”, check_str = “geeki”
Output : geeksforgeeks i
Explanation : i is last letter in freak to be present in string. The string is printed till first occurrence of i.
方法 #1:使用all() +切片+循环
在这种情况下,子字符串被构造到循环中的当前索引,然后从字符串,使用 all() 检查来自其他字符串的所有元素。如果全部都存在,则返回子字符串。
Python3
# Python3 code to demonstrate working of
# Extract String till all occurrence of characters from other string
# Using all() + slicing + loop
# initializing string
test_str = "geeksforgeeks is best for all geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing check string
check_str = "freak"
for idx in range(1, len(test_str)):
temp = test_str[:idx]
# checking for all chars of check_str in substring
if all([char in temp for char in check_str]):
res = temp
break
# printing result
print("String till all characters occurred : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract String till all occurrence of characters from other string
# Using find() + max() + slice
# initializing string
test_str = "geeksforgeeks is best for all geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing check string
check_str = "freak"
# max() find maximum index of all characters
res = test_str[:max([test_str.find(idx) for idx in check_str]) + 1]
# printing result
print("String till all characters occurred : " + str(res))
输出:
The original string is : geeksforgeeks is best for all geeks
String till all characters occurred : geeksforgeeks is best for a
方法 #2:使用find() + max() +切片
在这里,检查字符串中的每个字符都被迭代,检查所有的索引并记录其中的最大值。切片直到最大索引的子串是必需的答案。
蟒蛇3
# Python3 code to demonstrate working of
# Extract String till all occurrence of characters from other string
# Using find() + max() + slice
# initializing string
test_str = "geeksforgeeks is best for all geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing check string
check_str = "freak"
# max() find maximum index of all characters
res = test_str[:max([test_str.find(idx) for idx in check_str]) + 1]
# printing result
print("String till all characters occurred : " + str(res))
输出:
The original string is : geeksforgeeks is best for all geeks
String till all characters occurred : geeksforgeeks is best for a