3

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.

1
  • Note that += on strings in loops is O(n²) and should thus be avoided. Although trivial answers exist for this, the typical transformation would be to make a list and call .append in the loop. Then do a "".join afterwards. Commented Mar 9, 2015 at 10:05

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

4 Comments

You could - but why'd you want to get a regex engine involved in something so simple that can be achieved by Antti's answer that'll be faster and involve less overhead?
@JonClements The beauty of programming is the multitude of solutions, I just wanted to mention another. Otherwise, I would have simply repeated Antii.
Guess we could throw in concat_str = ''.join('-' for ch in title) then :p
@MalikBrahimi: the beauty of programming in Python is that there should be one obvious way to do it. #Zen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.