我已经设法在Python中编写一个小代码片段,它生成一个字符条,其长度等于另一个字符串的长度,如下所示:
title = "This is a string"
concat_str = ""
for i in range (0,len(title)): #len(title) == 16
concat_str += '-'
# resulting string
print(concat_str) # ----------------
Run Code Online (Sandbox Code Playgroud)
不过,我想知道这是否是实现这一目标的最pythonic方式.非常感谢.
最pythonic的方式是:
concat_str = '-' * len(title)
Run Code Online (Sandbox Code Playgroud)
PS你不需要指定0作为范围的开始:range(len(title))更多Pythonic.