Python – Concatenate Ranged Values in String list

Given list of strings, perform concatenation of ranged values from Strings list.

Input : test_list = [“abGFGcs”, “cdforef”, “asalloi”], i, j = 3, 5
Output : FGorll
Explanation : All string sliced, FG, or and ll from all three strings and concatenated.

Input : test_list = [“aGFGcs”, “cforef”, “aalloi”], i, j = 1, 4
Output : GFGforall
Explanation : Similar slicing operation different ranges.

Method #1 : Using loop + string slicing

This is brute way in which this task can be performed. In this we iterate for all strings and perform concatenation of values of range of each string.



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output

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

Method #2  : Using list comprehension + string slicing

This is yet another way in which this task can be performed. In this, we extract a particular range of string in one liner using list comprehension and string slicing as above method. 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.