Python 将字符串重复到一定长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3391076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:48:13  来源:igfitidea点击:

Repeat string to certain length

stringpythonrepeat

提问by John Howard

What is an efficient way to repeat a string to a certain length? Eg: repeat('abc', 7) -> 'abcabca'

将字符串重复到特定长度的有效方法是什么?例如: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?

有没有更好(更pythonic)的方法来做到这一点?也许使用列表理解?

采纳答案by Jason Scheirer

def repeat_to_length(string_to_expand, length):
   return (string_to_expand * ((length/len(string_to_expand))+1))[:length]

For python3:

对于python3:

def repeat_to_length(string_to_expand, length):
    return (string_to_expand * (int(length/len(string_to_expand))+1))[:length]

回答by zwol

Jason Scheirer's answer is correct but could use some more exposition.

Jason Scheirer 的回答是正确的,但可以使用更多的说明。

First off, to repeat a string an integer number of times, you can use overloaded multiplication:

首先,要将字符串重复整数次,您可以使用重载乘法:

>>> 'abc' * 7
'abcabcabcabcabcabcabc'

So, to repeat a string until it's at leastas 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:

因此,要重复一个字符串,直到它至少与您想要的长度一样长,您可以计算适当的重复次数并将其放在该乘法运算符的右侧:

def repeat_to_at_least_length(s, wanted):
    return s * (wanted//len(s) + 1)

>>> repeat_to_at_least_length('abc', 7)
'abcabcabc'

Then, you can trim it to the exact length you want with an array slice:

然后,您可以使用数组切片将其修剪为您想要的确切长度:

def repeat_to_length(s, wanted):
    return (s * (wanted//len(s) + 1))[:wanted]

>>> repeat_to_length('abc', 7)
'abcabca'

Alternatively, as suggested in pillmod's answerthat probably nobody scrolls down far enough to notice anymore, you can use divmodto compute the number of full repetitions needed, and the number of extra characters, all at once:

或者,正如pillmod 的回答中所建议的那样,可能没有人向下滚动到足以再注意到的程度,您可以使用一次divmod计算所需的完整重复次数和额外字符数:

def pillmod_repeat_to_length(s, wanted):
    a, b = divmod(wanted, len(s))
    return s * a + s[:b]

Which is better? Let's benchmark it:

哪个更好?让我们对其进行基准测试:

>>> import timeit
>>> timeit.repeat('scheirer_repeat_to_length("abcdefg", 129)', globals=globals())
[0.3964178159367293, 0.32557755894958973, 0.32851039397064596]
>>> timeit.repeat('pillmod_repeat_to_length("abcdefg", 129)', globals=globals())
[0.5276265419088304, 0.46511475392617285, 0.46291469305288047]

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.

所以,pillmod 的版本慢了 40%,这太糟糕了,因为我个人认为它更具可读性。这有几个可能的原因,首先是将其编译为大约 40% 以上的字节码指令。

Note: these examples use the new-ish //operator for truncating integer division. This is often calleda Python 3 feature, but according to PEP 238, it was introduced all the way back in Python 2.2. You only haveto use it in Python 3 (or in modules that have from __future__ import division) but you canuse it regardless.

注意:这些示例使用 new-ish//运算符来截断整数除法。这通常被称为Python 3 功能,但根据PEP 238,它一直在 Python 2.2 中引入。你只拥有在Python 3(或在具有模块使用它from __future__ import division),但你可以不考虑使用它。

回答by murgatroid99

How about string * (length / len(string)) + string[0:(length % len(string))]

怎么样 string * (length / len(string)) + string[0:(length % len(string))]

回答by vezult

This is one way to do it using a list comprehension, though it's increasingly wasteful as the length of the rptstring increases.

这是使用列表推导式的一种方法,尽管随着rpt字符串长度的增加,它会越来越浪费。

def repeat(rpt, length):
    return ''.join([rpt for x in range(0, (len(rpt) % length))])[:length]

回答by kennytm

from itertools import cycle, islice
def srepeat(string, n):
   return ''.join(islice(cycle(string), n))

回答by pillmuncher

def rep(s, m):
    a, b = divmod(m, len(s))
    return s * a + s[:b]

回答by Triptych

Yay recursion!

耶递归!

def trunc(s,l):
    if l > 0:
        return s[:l] + trunc(s, l - len(s))
    return ''

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.

我承认我刚刚读了 Little Schemer,我现在喜欢递归。

回答by Adam Parkin

Perhaps not the most efficient solution, but certainly short & simple:

也许不是最有效的解决方案,但肯定简短而简单:

def repstr(string, length):
    return (string * length)[0:length]

repstr("foobar", 14)

Gives "foobarfoobarfo". One thing about this version is that if length < len(string) then the output string will be truncated. For example:

给出“foobarfoobarfo”。关于这个版本的一件事是,如果长度 < len(string) 那么输出字符串将被截断。例如:

repstr("foobar", 3)

Gives "foo".

给出“foo”。

Edit: actually to my surprise, this is faster than the currently accepted solution (the 'repeat_to_length' function), at least on short strings:

编辑:实际上令我惊讶的是,这比当前接受的解决方案('repeat_to_length' 函数)更快,至少在短字符串上:

from timeit import Timer
t1 = Timer("repstr('foofoo', 30)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo', 30)", 'from __main__ import repeat_to_length')
t1.timeit()  # gives ~0.35 secs
t2.timeit()  # gives ~0.43 secs

Presumably if the string was long, or length was very high (that is, if the wastefulness of the string * lengthpart was high) then it would perform poorly. And in fact we can modify the above to verify this:

据推测,如果字符串很长,或者长度非常长(也就是说,如果string * length部分的浪费很大),那么它的表现就会很差。事实上,我们可以修改上面的内容来验证这一点:

from timeit import Timer
t1 = Timer("repstr('foofoo' * 10, 3000)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo' * 10, 3000)", 'from __main__ import repeat_to_length')
t1.timeit()  # gives ~18.85 secs
t2.timeit()  # gives ~1.13 secs

回答by Ale? Kotnik

Another FP aproach:

另一种 FP 方法:

def repeat_string(string_to_repeat, repetitions):
    return ''.join([ string_to_repeat for n in range(repetitions)])

回答by Amy Platt

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:

并不是说这个问题没有足够的答案,而是有一个重复功能;只需要制作一个列表然后加入输出:

from itertools import repeat

def rep(s,n):
  ''.join(list(repeat(s,n))