Python程序从字符串列表中提取给定范围内的字符
给定一个字符串列表,提取跨越整个字符串列表的索引范围内的字符。
Input : test_list = [“geeksforgeeks”, “is”, “best”, “for”, “geeks”], strt, end = 14, 20
Output : sbest
Explanation : Once concatenated, 14 – 20 range is extracted.
Input : test_list = [“geeksforgeeks”, “is”, “best”, “for”, “geeks”], strt, end = 11, 20
Output : sbesbest
Explanation : Once concatenated, 11 – 20 range is extracted.
方法 1:使用 join() + 列表理解
在此,我们使用 join() 和列表理解执行所有字符串的连接,然后发布,提取所需的字符范围。
Python3
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing char range
strt, end = 14, 30
# strt and end used to get desired characters
res = ''.join([sub for sub in test_list])[strt : end]
# printing result
print("Range characters : " + str(res))
Python3
# import module
from itertools import chain
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing char range
strt, end = 14, 30
# strt and end used to get desired characters
res = ''.join(chain.from_iterable(test_list))[strt : end]
# printing result
print("Range characters : " + str(res))
输出
The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Range characters : sbestforgeeks
方法 2:使用 chain.from_iterable() + join()
在此,我们使用 chain.from_iterable() 执行扁平化字符的任务,之后使用 join() 连接所有字符串并在范围内提取索引。
蟒蛇3
# import module
from itertools import chain
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing char range
strt, end = 14, 30
# strt and end used to get desired characters
res = ''.join(chain.from_iterable(test_list))[strt : end]
# printing result
print("Range characters : " + str(res))
输出
The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Range characters : sbestforgeeks