我一直在recntly做一些Python代碼,並希望做到以下幾點:拆分的話到變量
import shlex
shlex.split("this is a test")
print (shlex.split("this is a test"))
它的工作原理,但我想存儲分割短語,不同的變量,如果有人能幫助我,會很棒。謝謝!
我一直在recntly做一些Python代碼,並希望做到以下幾點:拆分的話到變量
import shlex
shlex.split("this is a test")
print (shlex.split("this is a test"))
它的工作原理,但我想存儲分割短語,不同的變量,如果有人能幫助我,會很棒。謝謝!
是否這樣?
>>> str = "this is a test"
>>> arr = str.split(" ")
>>> arr
['this', 'is', 'a', 'test']
>>> arr[0]
'this'
>>> a = arr[0]
>>> b = arr[1]
>>> c = arr[2]
>>> d = arr[3]
>>> a
'this'
或'a,b,c,d = arr' – 2014-09-04 11:22:38
split()
返回一個列表。既然你可能不知道會有多少單詞,你不能聲明你需要的所有單個變量。相反,你應該使用返回的列表,並使用它作爲適當的:
words = shlex.split("this is a test");
注意,這個存儲單詞列表中單變量,而不是試圖每個單詞存儲在其自己的變量。我建議你學習更多關於如何操作Python中的列表。
你爲什麼要將它們存儲在變量中?你打算怎麼處理他們? – thefourtheye 2014-09-04 11:09:53
這是一個複雜的項目,但爲了讓代碼理解它們,它會喜歡,存儲每個單詞並定義它們。所以我只是想把它們存儲爲字符串。 – Matt 2014-09-04 11:11:58
爲什麼不把它列入清單?這將使迭代變得容易。 – 2014-09-04 11:13:17