gpt4 book ai didi

python - 如何在 Python 中正确生成可变字符串模式

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:13 26 4
gpt4 key购买 nike

我设法用 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) # ----------------

不过,我想知道这是否是实现它的最 pythonic 方式。非常感谢。

最佳答案

最pythonic的方式是:

concat_str = '-' * len(title)

附言您不需要将 0 指定为范围的开始:range(len(title)) 更符合 Pythonic。

关于python - 如何在 Python 中正确生成可变字符串模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28929979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com