我有一个python列表作为字符串,我想把它打印出来,间隔在和之间

2024-09-30 01:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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'

我怎样才能像“lowr”一样打印出来,在它们之间放置一个空格字符而不使用循环?所以看起来像“l-o-w-r”


Tags: ofthetoinfromhello列表world
3条回答

字符串有一个^{}方法,它将用中间给出的字符串将迭代的元素结合在一起。例如

>>> x = 'hello world'
>>> sep = ' '  # your separator is a space
>>> sep.join(x[2:10:2])
'l o w r'

查看Python的str.join()函数。它允许您连接任何iterable,同时在.join()中的引号""之间插入任何内容。你知道吗

像这样:

x = "hello world"

" ".join(x[2:10:2])

只要用一个空格或-将列表中的字符连接起来就可以了。它使用一个join,它给出一个由给定分隔符从列表元素缝合在一起的字符串

x = "hello world"
print(' '.join(x[2:10:2]))
#l o w r
print('-'.join(x[2:10:2]))
#l-o-w-r

相关问题 更多 >

    热门问题