Python – String Repetition and spacing in List
Sometimes while working with Python, we can have a problem in which we need to perform the repetion 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.
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.
The original list is : ['gfg', 'is', 'best'] List after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course