Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly generate a variable string pattern in Python

Tags:

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.

like image 476
Alejandro Ricoveri Avatar asked Sep 19 '26 00:09

Alejandro Ricoveri


2 Answers

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.

like image 170

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

concat_str = re.sub('.', '-', title)
like image 33
Malik Brahimi Avatar answered Sep 20 '26 15:09

Malik Brahimi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!