簡體   English   中英

在python中將字符串轉換為元組

[英]converting string to tuple in python

我有一個從類似"('mono')"類的軟件返回的字符串,我需要將字符串轉換為元組。

我當時在想使用ast.literal_eval("('mono')")但它說的是格式錯誤的字符串。

由於需要元組,因此在某些情況下,您必須期望包含不止元素的列表。 不幸的是,您沒有給出瑣碎的示例(mono) ,因此我們不得不猜測。 這是我的猜測:

"(mono)"
"(two,elements)"
"(even,more,elements)"

如果您的所有數據都是這樣,請通過分割字符串(減去周圍的括號)將其轉換為列表,然后調用元組構造函數。 即使在單元素情況下也可以使用:

assert data[0] == "(" and data[-1] == ")"
elements = data[1:-1].split(",")
mytuple = tuple(elements)

或者一步: elements = tuple(data[1:-1].split(",")) 如果您的數據看起來並不像我的例子,編輯你的問題 ,以提供更多的細節。

使用正則表達式怎么樣?

In [1686]: x
Out[1686]: '(mono)'

In [1687]: tuple(re.findall(r'[\w]+', x))
Out[1687]: ('mono',)

In [1688]: x = '(mono), (tono), (us)'

In [1689]: tuple(re.findall(r'[\w]+', x))
Out[1689]: ('mono', 'tono', 'us')

In [1690]: x = '(mono, tonous)'

In [1691]: tuple(re.findall(r'[\w]+', x))
Out[1691]: ('mono', 'tonous')

試試這個

a = ('mono')
print tuple(a)      # <-- you create a tuple from a sequence 
                    #(which is a string)
print tuple([a])    # <-- you create a tuple from a sequence 
                    #(which is a list containing a string)
print tuple(list(a))# <-- you create a tuple from a sequence 
                    #     (which you create from a string)
print (a,)# <-- you create a tuple containing the string
print (a)

輸出:

('m', 'o', 'n', 'o')
('mono',)
('m', 'o', 'n', 'o')
('mono',)
mono

我假設所需的輸出是帶有單個字符串的元組:('mono',)

一個元組的末尾逗號為(tup,)形式

a = '(mono)'
a = a[1:-1] # 'mono': note that the parenthesis are removed removed 
            # if they are inside the quotes they are treated as part of the string!
b = tuple([a]) 
b
> ('mono',)
# the final line converts the string to a list of length one, and then the list to a tuple

將字符串轉換為元組? 只需應用tuple

>>> tuple('(mono)')
('(', 'm', 'o', 'n', 'o', ')')

現在是一個元組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM