2015-11-19 93 views
1

我有一個這樣的字符串,從文本文件中讀取行後:字符串元組轉換在python

To = "'[email protected]','[email protected]','[email protected]','[email protected]','[email protected]'" 

我想將其轉換爲一個元組。我做的是:

To = (To,) 
type(To) #o/p tuple 
len(To) #1 
To 
("'[email protected]','[email protected]','[email protected]', '[email protected]','[email protected]'",) # output tuple 

預期的那樣,我需要通過,每個值分開,它從字符串或元組轉換後存儲到一個元組:

To 
('[email protected]','[email protected]','[email protected]', '[email protected]','[email protected]',) # output tuple 
len(To) #should give 5 
+0

我回答了你幾個小時前問過的鏈接副本中的問題。 – TigerhawkT3

回答

2

或者,如果你不想使用AST,你可以簡單地運行:

tuple(word[1:-1] for word in To.split(",")) 
+0

直到現在最簡單的方法。 – Satya

2

注:

  • 你可以在,
  • String轉換成List通過拆分,那麼你可以轉換成ListTuple

代碼:

To = "'[email protected]','[email protected]','[email protected]','[email protected]','[email protected]'" 
print tuple(To.split(",")) 

輸出:

("'[email protected]'", "'[email protected]'", "'[email protected]'", "'[email protected]'", "'[email protected]'") 

如果你想刪除'報價

代碼1:

print tuple(elem.strip("'") for elem in To.split(",")) 

輸出1:

('[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]') 
+0

感謝Vignesh的詳細解答。 – Satya