[英]python3 string “abcd” print: aababcabcd?
If a have a string like abcd
or 1234
etc. how can I print together, the first character, then the first two characters, then the first three etc. all together? 如果有一个像abcd
或1234
等的字符串,我怎么能一起打印,第一个字符,然后是前两个字符,然后是前三个等等?
For example for a string = 1234
I would like to print/return 1121231234
or aababcabcd
例如,对于string = 1234
我想打印/返回1121231234
或aababcabcd
I have this code so far: 到目前为止我有这个代码:
def string_splosion(str):
i = 0
while i <= len(str):
i += 1
print(str[:i])
print(string_splosion('abcd'))
But it prints/returns it in separate lines. 但它以单独的行打印/返回它。 I could write it manually as print(str[0:1], str[1:2] <...>)
but how do I make python do it as I don't know how long the string is going to be? 我可以手动编写它作为print(str[0:1], str[1:2] <...>)
但是如何让python做它因为我不知道字符串将会有多长?
You shouldn't use str
as a variable name, because it shadows the built-in str
type . 您不应该将str
用作变量名,因为它会影响内置的str
类型 。 You could join the sliced strings together in your loop: 您可以在循环中将切片的字符串连接在一起:
def string_splosion(string):
i, result = 0, ''
while i < len(string): # < instead of <=
i += 1
result += string[:i]
return result
It's possible to shorten your code a little using str.join
and range
: 使用str.join
和range
可以缩短你的代码:
def string_splosion(string):
return ''.join(string[:i] for i in range(1, len(string) + 1))
or using itertools.accumulate
(Python 3.2+): 或使用itertools.accumulate
(Python 3.2+):
import itertools
def string_splosion(string):
return ''.join(itertools.accumulate(string))
itertools.accumulate
approach appears to be 2 times faster than str.join
one and about 1.5 times faster than the original loop-based solution: itertools.accumulate
方法似乎比str.join
快2倍,比原始基于循环的解决方案快约1.5倍:
string_splosion_loop(abcdef): 2.3944241080715223
string_splosion_join_gen(abcdef): 2.757582983268288
string_splosion_join_lc(abcdef): 2.2879220573578865
string_splosion_itertools(abcdef): 1.1873638161591886
The code I used to time the functions is 我用来计算函数的代码是
import itertools
from timeit import timeit
string = 'abcdef'
def string_splosion_loop():
i, result = 0, ''
while i < len(string):
i += 1
result += string[:i]
return result
def string_splosion_join_gen():
return ''.join(string[:i] for i in range(1, len(string) + 1))
def string_splosion_join_lc():
# str.join performs faster when the argument is a list
return ''.join([string[:i] for i in range(1, len(string) + 1)])
def string_splosion_itertools():
return ''.join(itertools.accumulate(string))
funcs = (string_splosion_loop, string_splosion_join_gen,
string_splosion_join_lc, string_splosion_itertools)
for f in funcs:
print('{.__name__}({}): {}'.format(f, string, timeit(f)))
Just use: 只需使用:
"".join([s[:i] for i in range(len(s)+1)])
As @abc noted, don't use str
as a variable name because it's one of the default type. 正如@abc所指出的,不要将str
用作变量名,因为它是默认类型之一。 see https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange 请参阅https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange
Eg: 例如:
>>> s = "1234"
>>> "".join([s[:i] for i in range(len(s)+1)])
'1121231234'
>>> s = "abcd"
>>> "".join([s[:i] for i in range(len(s)+1)])
'aababcabcd'
range(len(s)+1)
is because of slicing, see Explain Python's slice notation : range(len(s)+1)
是因为切片,请参阅Explain Python的切片表示法 :
>>> s = "1234"
>>> len(s)
4
>>> range(len(s))
[0, 1, 2, 3]
>>> s[:3]
'123'
>>> range(len(s)+1)
[0, 1, 2, 3, 4]
>>> s[:4]
'1234'
Then: 然后:
>>> s[:0]
''
>>> s[:1]
'1'
>>> s[:2]
'12'
>>> s[:3]
'123'
>>> s[:4]
'1234'
Lastly, join list([s[:1], s[:2], s[:3], s[:4]])
using "".join(list)
, see https://docs.python.org/2/library/string.html#string.join : 最后,使用"".join(list)
加入list([s[:1], s[:2], s[:3], s[:4]])
"".join(list)
,请参阅https://docs.python.org /2/library/string.html#string.join :
>>> list([s[:1], s[:2], s[:3], s[:4]])
['1', '12', '123', '1234']
>>> x = list([s[:1], s[:2], s[:3], s[:4]])
>>> "".join(x)
'1121231234'
>>> "-".join(x)
'1-12-123-1234'
>>> " ".join(x)
'1 12 123 1234'
To avoid extract iteration in loop, you can use range(1,len(s)+1)
since s[:0]
returns string of 0 length: 为了避免循环中的提取迭代,可以使用range(1,len(s)+1)
因为s[:0]
返回0长度的字符串:
>>> s = "1234"
>>> "".join([s[:i] for i in range(1,len(s)+1)])
'1121231234'
>>> "".join([s[:i] for i in range(len(s)+1)])
'1121231234'
If you are using python 3 you can use this to print without a newline: 如果你使用python 3,你可以使用它来打印没有换行符:
print(yourString, end="")
So your function could be: 所以你的功能可能是:
def string_splosion(str):
for i in range(len(str)):
print(str[:i], end="")
print(string_splosion('abcd'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.