[英]I have a python list as strings and i want to print it out as spaced between and sequential
I have a python list and i want to print them in an sequential order and spaced between them我有一个 python 列表,我想按顺序打印它们并在它们之间隔开
x = "hello world"
>>> x[2:10] # this prints from 'l' to 'd' allway
>>> x[2:10:2] # this prints from 'l' to 'd' in the order of two,
'lowr'
how can i print it like 'lowr ', putting a space character between them without a loop?我怎样才能像'lowr'一样打印它,在它们之间放置一个空格字符而不循环? So it would look like 'low-r'
所以它看起来像'low-r'
Check out Python's str.join() function.查看 Python 的str.join()函数。 It lets you join any iterable whilst inserting whatever you put in between the quotes
""
in .join()
.它允许您加入任何可迭代对象,同时插入您在
.join()
的引号""
之间放入的任何内容。
Like so:像这样:
x = "hello world"
" ".join(x[2:10:2])
Just join the characters in the list with a single space, or with a -
, as you feel like.只需将列表中的字符用一个空格或
-
,就可以了。 This uses a join which gives you a string stitched together from the elements of the list by the given separator这使用了一个连接,它为您提供了一个由给定分隔符从列表元素拼接在一起的字符串
x = "hello world"
print(' '.join(x[2:10:2]))
#l o w r
print('-'.join(x[2:10:2]))
#l-o-w-r
Not sure what you mean by without a loop, but you could do the following:不确定没有循环是什么意思,但您可以执行以下操作:
x = "hello world"
' '.join(y for y in x[2:10:2])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.