Skip to content
Related Articles

Related Articles

Python – String Repetition and spacing in List

View Discussion
Improve Article
Save Article
  • Last Updated : 25 Oct, 2021
View Discussion
Improve Article
Save Article

Sometimes while working with Python, we can have a problem in which we need to perform the repetition of each string in list and also attach a deliminator to each occurrence. This kind of problem can occur in day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop 
This task can be performed in brute force way using loop. In this, we iterate the list and perform string addition and multiplication while iteration using suitable operators.
 

Python3




# Python3 code to demonstrate working of
# String Repetition and spacing in List
# Using loop
 
# initializing list
test_list = ['gfg', 'is', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = '-'
 
# initializing K
K = 3
 
# String Repetition and spacing in List
# Using loop
res = []
for sub in test_list:
    res.append((sub + delim) * K)
     
# printing result
print("List after performing operations : " + str(res))

Output : 

The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg-', 'is-is-is-', 'best-best-best-']

 

 
Method #2 : Using join() + list comprehension 
The combination of above functionalities can also be used to perform this task. In this, we perform the task of attaching delim using join() and list comprehension performs the task of repetition. Avoids trailing delim.
 

Python3




# Python3 code to demonstrate working of
# String Repetition and spacing in List
# Using join() + list comprehension
 
# initializing list
test_list = ['gfg', 'is', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = '-'
 
# initializing K
K = 3
 
# String Repetition and spacing in List
# Using join() + list comprehension
res = []
for sub in test_list:
    res.append(delim.join([sub for _ in range(K)]))
     
# printing result
print("List after performing operations : " + str(res))

Output : 

The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best']

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!