【发布时间】:2009-01-30 20:27:49
【问题描述】:
在 Perl 中,我可以使用 'x' 运算符复制字符串:
$str = "x" x 5;
我可以在 Python 中做类似的事情吗?
【问题讨论】:
在 Perl 中,我可以使用 'x' 运算符复制字符串:
$str = "x" x 5;
我可以在 Python 中做类似的事情吗?
【问题讨论】:
>>> "blah" * 5
'blahblahblahblahblah'
【讨论】:
这是对官方 Python3 文档的参考:
https://docs.python.org/3/library/stdtypes.html#string-methods
字符串实现所有common 序列操作...
...这导致我们:
https://docs.python.org/3/library/stdtypes.html#typesseq-common
Operation | Result
s * n or n * s | n shallow copies of s concatenated
例子:
>>> 'a' * 5
'aaaaa'
>>> 5 * 'b'
'bbbbb'
【讨论】:
在 Perl 中 (man perlop) x 是 called repetition operator。
在 Python 3 中,此 * 也是 referred to 作为 repetition operator。
在 Python 2 中它可能被称为相同的东西,但我只在内置运算符下将 found it referred 改为 sequence repetition。
我认为离题很重要,字符串不是运算符的唯一用途;还有一些:
"ab"x5 产生"ababababab"
"ab"*5 相同。@ones = (1) x @ones 分配每个数组元素而不重新分配引用。ones = [1] * len(ones) 看起来像相同的结果,但重新分配了引用。(0)x5 生成 ((0),(0),(0),(0),(0))。[[0]]*5 是 [[0],[0],[0],[0],[0]]
然而,正如上面“几乎”所暗示的那样,Python 中有一个警告(来自文档):
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
同样在 Perl 中,我不确定它记录在哪里,但空列表与运算符的行为有点不同,可能是因为它与 False 等效。
@one=((1))x5;
say(scalar @one); # 5
@arr=(())x5;
say(scalar @arr); # 0
【讨论】: