Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-将字符串拆分两次_Python - Fatal编程技术网

Python-将字符串拆分两次

Python-将字符串拆分两次,python,Python,我有一些数据看起来像“string,string,string:otherstring,otherstring,otherstring” 我想一次一个地操作第一组“字符串”。如果我分割输入并根据冒号对其进行分隔,那么我将得到一个列表。然后,我无法再次拆分它,因为“'list'对象没有属性'split'”。或者,如果我决定基于逗号进行定界,那么它将返回所有内容(包括逗号后面的内容,我不想操纵这些内容)。rsplit也有同样的问题。现在,即使有一个列表,我仍然可以通过使用[0]、[1]等操作第一个条

我有一些数据看起来像“string,string,string:otherstring,otherstring,otherstring”

我想一次一个地操作第一组“字符串”。如果我分割输入并根据冒号对其进行分隔,那么我将得到一个列表。然后,我无法再次拆分它,因为“'list'对象没有属性'split'”。或者,如果我决定基于逗号进行定界,那么它将返回所有内容(包括逗号后面的内容,我不想操纵这些内容)。rsplit也有同样的问题。现在,即使有一个列表,我仍然可以通过使用[0]、[1]等操作第一个条目。除了“字符串”的数量总是在变化之外,所以我无法将数字硬编码到位。关于如何绕过这个列表限制有什么想法吗

试试这个:

import re

s = 'string,string,string:otherstring,otherstring,otherstring'
re.split(r'[,:]', s)
=> ['string', 'string', 'string', 'otherstring', 'otherstring', 'other string']
我们使用正则表达式和方法来拆分具有多个分隔符的字符串。或者,如果您想以与第二组不同的方式操作第一组字符串,我们可以创建两个列表,每个列表中都有字符串:

[x.split(',') for x in s.split(':')]
=> [['string', 'string', 'string'], ['otherstring', 'otherstring', 'otherstring']]
…或者,如果您只想检索第一个组中的字符串,只需执行以下操作:

s.split(':')[0].split(',')
=> ['string', 'string', 'string']
使用一对
join()
语句将其转换回字符串:

>>> string = "string,string,string:otherstring,otherstring,otherstring"
>>> ' '.join(' '.join(string.split(':')).split(',')).split()
['string', 'string', 'string', 'otherstring', 'otherstring', 'otherstring']
>>> 

['string','string','string','otherstring','otherstring','otherstring','otherstring'].

您可能想看看这个解决方案,它将发布一个带有列表comps和chains的答案,但这更干净。谢谢您的编辑。我一定解释得不够透彻,因为问题是我不需要处理逗号后面的任何字符串(这就是为什么我将示例命名为“string”和“otherstring”)。不过,您的x.split想法现在可能会解决我的问题,因为我将只处理第一个“组”的内容。谢谢。@Peter是的,问题不清楚。但现在它是!请看我的最新更新,就这样。请不要忘记回答这个问题;)
text = "string,string,string:otherstring,otherstring,otherstring"
replace = text.replace(":", ",").split(",")
print(replace)