Alejandro Ricoveri
Alejandro Ricoveri

Reputation: 917

How to properly generate a variable string pattern in Python

I have managed to code a little snippet in Python which generates a character strip whose length equals the length of another string like so:

title = "This is a string"
concat_str = ""
for i in range (0,len(title)): #len(title) == 16
  concat_str += '-'
# resulting string
print(concat_str) # ----------------

Nevertheless, I wish to know whether this is the most pythonic way to implement this. Thanks a lot.

Upvotes: 3

Views: 96

Answers (2)

Malik Brahimi
Malik Brahimi

Reputation: 16711

You can use regex to replace all characters with a dash:

concat_str = re.sub('.', '-', title)

Upvotes: 1

The most pythonic way would be:

concat_str = '-' * len(title)

P.S. You do not need to specify 0 as the start for range: range(len(title)) is more Pythonic.

Upvotes: 8

Related Questions