如何获取字符列表中的所有子字符串(python)

2024-10-01 07:43:46 发布

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

我想遍历一个字符列表

temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']

{cd2>可以得到两个

我目前的方法是:

^{pr2}$

问题是这个打印出来了

['h', 'e', 'l', 'l', 'o']
['e', 'l', 'l', 'o']
['l', 'l', 'o']
['l', 'o']
['o']

等等。我怎么才能只打印出完整的有效字符串?在

编辑:我应该更具体地说明什么是“有效”字符串。只要字符串中的所有字符都是字母或数字,字符串就有效。我没有在我的检查条件中包含“isnumerical()”方法,因为它与问题没有特别的关系。在


Tags: 方法字符串编辑列表关系字母数字条件
3条回答

你可以这样做:

''.join(temp).split('#')

如果您只想要helloworld,并且您的单词总是#分开,那么可以通过使用^{}和{a2}轻松完成

>>> temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']
>>> "".join(temp).split('#')
['hello', 'world']

如果您需要print您需要的完整有效字符串

^{pr2}$

List具有返回元素位置的方法index。可以使用切片来连接字符。在

In [10]: temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']
In [11]: pos = temp.index('#')
In [14]: ''.join(temp[:pos])
Out[14]: 'hello'
In [17]: ''.join(temp[pos+1:])
Out[17]: 'world'

相关问题 更多 >