2010-05-11 71 views
1

我有一段文字是被递给我喜欢:解析ASCII文本字符串转换成独立的变量

这里是一条线\ n \ nhere是双线\ n \ nhere为三

线

我想要做的是将这个字符串分成三个单独的变量。 我不太清楚在python中如何实现这个功能。

感谢您的帮助, JML

回答

4
a, b, c = s.split('\n\n') 
+0

它看起来像将s变成列表元素。我如何索引它? – jml 2010-05-11 22:04:02

+2

它不会修改's'。字符串是不可变的,所以字符串操作返回一个新的对象。 – 2010-05-11 22:07:58

0

要使用3个元素分解成一个列表:

mystring = "here is line one\n\nhere is line two\n\nhere is line three" 
listofthings = mystring.split("\n\n") 

然后你可以用listofthings[0]listofthings[1]listofthings[2]访问它们。

把他们在不同的实际变量:

mystring = "here is line one\n\nhere is line two\n\nhere is line three" 
a,b,c = mystring.split("\n\n") 

# a now contains "here is line one", et cetera. 
+1

'mystring.split()'将分割空白和末尾。 – tdedecko 2010-05-11 22:07:21

+0

哎呀,你是对的。这就是我醒来后立即发布的内容。固定。 – Amber 2010-05-11 22:57:38

1
s1, s2, s3 = that_string_variable.split('\n\n') 

基本上,任何变量,你已经得到了在该字符串,然后你在你想要作为分隔符使用令牌.split()(在此情况下,'\n\n'),那会返回一个字符串列表。您可以使用“解包”进行分配,以指定要转至的每个元素的多个变量。像上面赋值说:“我知道右手边给我三个要素,我想那些进入s1s2s3的顺序

1

您可以使用拆分功能:

s = 'ab\n\ncd' 
tokens = s.split('\n\n') 

然后tokens是数组['ab', 'cd']

编辑:我以为你的意思是,你希望你的例子被分成3个字符串,但一般要分割字符串> 3串如有必要