簡體   English   中英

我有一個 python 列表作為字符串,我想將它打印出來作為間隔和順序

[英]I have a python list as strings and i want to print it out as spaced between and sequential

我有一個 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'一樣打印它,在它們之間放置一個空格字符而不循環? 所以它看起來像'low-r'

查看 Python 的str.join()函數。 它允許您加入任何可迭代對象,同時插入您在.join()的引號""之間放入的任何內容。

像這樣:

x = "hello world"

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

只需將列表中的字符用一個空格或- ,就可以了。 這使用了一個連接,它為您提供了一個由給定分隔符從列表元素拼接在一起的字符串

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

字符串有一個.join()方法,它將把那個可迭代對象的元素與你在中間給出的字符串連接在一起。 例如

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

不確定沒有循環是什么意思,但您可以執行以下操作:

x = "hello world"
' '.join(y for y in x[2:10:2])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM