简体   繁体   English

我有一个 python 列表作为字符串,我想将它打印出来作为间隔和顺序

[英]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

Strings have a .join() method which will join together the elements of that iterable with the string you give in the middle.字符串有一个.join()方法,它将把那个可迭代对象的元素与你在中间给出的字符串连接在一起。 For example例如

>>> x = 'hello world'
>>> sep = ' '  # your separator is a space
>>> sep.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.

相关问题 我想从 python 的列表中打印唯一的字符串,但它破坏了列表 - I want to print unique strings from a list in python but it breaks the list 我有多个字符串的列表,我想在字符串的 substring 中搜索一些模式,并在 python 中打印下一行模式 - I have list with multiple strings and I want to search some patterns in substring of the string and print the next, previous line of pattern in python 我想打印出列表的某个部分 - i want to print out a certain part of a list 我有一个以不同扩展名结尾的字符串列表,我如何告诉Python不要打印.zip字符串 - I have a list of strings that end with different extensions how would I tell Python to not print the .zip strings 我怎样才能做到这一点? 我正在尝试使用 python 按顺序打印所有数字的输入 - how can i achieve this ? I'm trying to have an Input that will print out all the numbers in sequential order using python 我想要一个子目录列表,然后打印它 - I want to have a list of subdirectories and then print it 如何打印行间距的二维列表元素? - How do I print out 2d list elements with line spaced? 我想打印 Python map 列表元素 - I want print Python map list element 我有字符串列表,我想删除符号并将其拆分 - I have list of strings and I want to remove symbols and split it 我有一个列表,其中是字符串,我想删除 [ ] - I have a list where is are strings, I want to remove the [ ]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM