Python|从元组范围切片字符串
有时,在处理数据时,我们可能会遇到需要根据指定的子字符串范围从字符串中删除的问题。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环+列表切片
这是执行此任务的蛮力任务。在此,我们通过使用列表切片小心地省略切片范围来重新制作字符串。元组的迭代是通过循环完成的。
# Python3 code to demonstrate working of
# Slice String from Tuple ranges
# using loop + list slicing
# initialize list and string
test_list = [(2, 4), (5, 9), (13, 17), (24, 27)]
test_str = "geeksforgeeks is best for geeks and programming"
# printing original list and string
print("The original list : " + str(test_list))
print("The original string : " + str(test_str))
# Slice String from Tuple ranges
# using loop + list slicing
for front, rear in reversed(test_list):
test_str = test_str[ : front] + test_str[rear + 1:]
# printing result
print("The String after slicing is : " + str(test_str))
输出 :
The original list : [(2, 4), (5, 9), (13, 17), (24, 27)]
The original string : geeksforgeeks is best for geeks and programming
The String after slicing is : geeksest foeks and programming
方法 #2:使用join() + any()
+ 生成器表达式
这些功能的组合也可用于执行此任务。在此,我们使用生成器表达式执行切片任务,排除由 any() 处理。修改后的字符串的创建是由 join() 完成的。
# Python3 code to demonstrate working of
# Slice String from Tuple ranges
# using join() + any() + generator expression
# initialize list and string
test_list = [(2, 4), (5, 9), (13, 17), (24, 27)]
test_str = "geeksforgeeks is best for geeks and programming"
# printing original list and string
print("The original list : " + str(test_list))
print("The original string : " + str(test_str))
# Slice String from Tuple ranges
# using join() + any() + generator expression
res = "".join(test_str[idx] for idx in range(len(test_str))\
if not any(front <= idx <= rear for front, rear in test_list))
# printing result
print("The String after slicing is : " + str(res))
输出 :
The original list : [(2, 4), (5, 9), (13, 17), (24, 27)]
The original string : geeksforgeeks is best for geeks and programming
The String after slicing is : geeksest foeks and programming