📜  Python – 在字符串列表中连接范围值

📅  最后修改于: 2022-05-13 01:54:29.707000             🧑  作者: Mango

Python – 在字符串列表中连接范围值

给定字符串列表,执行字符串列表中范围值的连接。

方法#1:使用循环+字符串切片

这是可以执行此任务的粗暴方式。在此我们迭代所有字符串并执行每个字符串范围值的连接。

Python3
# Python3 code to demonstrate working of 
# Concatenate Ranged Values in String list
# Using loop
  
# initializing list
test_list = ["abGFGcs", "cdforef", "asalloi"]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing range
i, j = 2, 5
  
res = ''
for ele in test_list:
      
    # Concatenating required range
    res += ele[i : j]
          
# printing result 
print("The Concatenated String : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Concatenate Ranged Values in String list
# Using list comprehension + string slicing
  
# initializing list
test_list = ["abGFGcs", "cdforef", "asalloi"]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing range
i, j = 2, 5
  
# join() used to join slices together
res = ''.join([sub[i : j] for sub in test_list])
          
# printing result 
print("The Concatenated String : " + str(res))


输出
The original list : ['abGFGcs', 'cdforef', 'asalloi']
The Concatenated String : GFGforall

方法#2:使用列表理解+字符串切片

这是可以执行此任务的另一种方式。在此,我们使用上述方法的列表理解和字符串切片在一个衬里中提取特定范围的字符串。

Python3

# Python3 code to demonstrate working of 
# Concatenate Ranged Values in String list
# Using list comprehension + string slicing
  
# initializing list
test_list = ["abGFGcs", "cdforef", "asalloi"]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing range
i, j = 2, 5
  
# join() used to join slices together
res = ''.join([sub[i : j] for sub in test_list])
          
# printing result 
print("The Concatenated String : " + str(res))
输出
The original list : ['abGFGcs', 'cdforef', 'asalloi']
The Concatenated String : GFGforall