如何在没有字符串连接的情况下在Python中重复字符? [英] How to repeat characters in Python without string concatenation?

查看:102
本文介绍了如何在没有字符串连接的情况下在Python中重复字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个简短的程序来进行频率分析.但是,有一行困扰着我:

I'm currently writing a short program that does frequency analysis. However, there's one line that is bothering me:

"{0[0]}  | " + "[]" * num_occurrences + " Total: {0[1]!s}"

Python中是否有一种方法可以重复某些字符任意次数而无需借助串联(最好是在格式字符串中)?我觉得我不是用最Python化的方式做到这一点的.

Is there a way in Python to repeat certain characters an arbitrary number of times without resorting to concatenation (preferably inside a format string)? I don't feel like I'm doing this in the most Pythonic way.

推荐答案

重复字符或字符串的最佳方法是将其相乘:

The best way to repeat a character or string is to multiply it:

>>> "a" * 3
'aaa'
>>> '123' * 3
'123123123'

在您的示例中,我可能会使用:

And for your example, I'd probably use:

>>> "{0[0]}  | {1} Total: {0[1]!s}".format(foo, "[]" * num_occurrences)

这篇关于如何在没有字符串连接的情况下在Python中重复字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆