将字符串重复到一定长度
将字符串重复到一定长度的有效方法是什么?例如:repeat('abc', 7) -> 'abcabca'
这是我当前的代码:
def repeat(string, length):
cur, old = 1, string
while len(string) < length:
string += old[cur-1]
cur = (cur+1)%len(old)
return string
是否有更好(更Pythonic)的方法来做到这一点?也许使用列表理解?
What is an efficient way to repeat a string to a certain length? Eg: repeat('abc', 7) -> 'abcabca'
Here is my current code:
def repeat(string, length):
cur, old = 1, string
while len(string) < length:
string += old[cur-1]
cur = (cur+1)%len(old)
return string
Is there a better (more pythonic) way to do this? Maybe using list comprehension?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
Jason Scheirer 的答案是正确的,但可以进行更多说明。
首先,要重复一个字符串整数次,您可以使用重载乘法:
因此,要重复一个字符串,直到它至少与您想要的长度一样长,您可以计算适当的次数重复并将其放在乘法运算符的右侧:
然后,您可以使用数组切片将其修剪为所需的精确长度:
或者,如 pillmod 的答案 可能没有人向下滚动足够远来注意到了,你可以使用
divmod
一次性计算所需的完整重复次数和额外字符数:哪个更好?让我们对其进行基准测试:
所以,pillmod 的版本大约慢了 40%,这太糟糕了,因为我个人认为它更具可读性。造成这种情况的可能原因有几个,首先是它编译的字节码指令增加了大约 40%。
注意:这些示例使用新的
//
运算符来截断整数除法。这通常被称为 Python 3 功能,但根据 PEP 238,它早在 Python 2.2 中就被引入了。您只需在 Python 3 中(或在具有 from __future__ import division 的模块中)使用它,但无论如何您都可以使用它。Jason Scheirer's answer is correct but could use some more exposition.
First off, to repeat a string an integer number of times, you can use overloaded multiplication:
So, to repeat a string until it's at least as long as the length you want, you calculate the appropriate number of repeats and put it on the right-hand side of that multiplication operator:
Then, you can trim it to the exact length you want with an array slice:
Alternatively, as suggested in pillmod's answer that probably nobody scrolls down far enough to notice anymore, you can use
divmod
to compute the number of full repetitions needed, and the number of extra characters, all at once:Which is better? Let's benchmark it:
So, pillmod's version is something like 40% slower, which is too bad, since personally I think it's much more readable. There are several possible reasons for this, starting with its compiling to about 40% more bytecode instructions.
Note: these examples use the new-ish
//
operator for truncating integer division. This is often called a Python 3 feature, but according to PEP 238, it was introduced all the way back in Python 2.2. You only have to use it in Python 3 (or in modules that havefrom __future__ import division
) but you can use it regardless.对于Python3:
For python3:
这是相当Pythonic的:
This is pretty pythonic:
也许不是最有效的解决方案,但肯定是简短且有效的解决方案。简单:
给出“foobarfoobarfo”。这个版本的一件事是,如果 length < len(string) 那么输出字符串将被截断。例如:
给出“foo”。
编辑:实际上令我惊讶的是,这比当前接受的解决方案(“repeat_to_length”函数)更快,至少在短字符串上:
大概如果字符串很长,或者长度非常高(也就是说,如果
string * length
部分很高),那么它的性能就会很差。事实上我们可以修改上面的内容来验证这一点:Perhaps not the most efficient solution, but certainly short & simple:
Gives "foobarfoobarfo". One thing about this version is that if length < len(string) then the output string will be truncated. For example:
Gives "foo".
Edit: actually to my surprise, this is faster than the currently accepted solution (the 'repeat_to_length' function), at least on short strings:
Presumably if the string was long, or length was very high (that is, if the wastefulness of the
string * length
part was high) then it would perform poorly. And in fact we can modify the above to verify this:我用这个:
i use this:
怎么样:
How about:
并不是说这个问题没有足够的答案,而是有一个重复功能;只需要列出一个列表,然后加入输出:
Not that there haven't been enough answers to this question, but there is a repeat function; just need to make a list of and then join the output:
耶递归!
不会永远扩展,但对于较小的字符串来说它很好。而且很漂亮。
我承认我刚刚读了《小阴谋家》,我现在喜欢递归。
Yay recursion!
Won't scale forever, but it's fine for smaller strings. And it's pretty.
I admit I just read the Little Schemer and I like recursion right now.
这是使用列表理解来实现此目的的一种方法,尽管随着
rpt
字符串长度的增加,这种方法越来越浪费。This is one way to do it using a list comprehension, though it's increasingly wasteful as the length of the
rpt
string increases.另一种 FP 方法:
Another FP aproach:
目前
print(f"{'abc'*7}")
生成:Currently
print(f"{'abc'*7}")
generates: