簡體   English   中英

如何從python列表中提取字符串?

[英]How to extract string from python list?

假設python數組“ myarray”包含:

mylist = [u'a',u'b',u'c']

我想要一個包含數組中所有元素的字符串,同時保留這樣的雙引號(注意如何沒有方括號,而是括號):

result = "('a','b','c')"

我嘗試使用",".join(mylist) ,但是它給了我“ a,b,c”的結果,並消除了單引號。

您距離很近,這就是我要做的:

result = "('%s')" % "','".join(mylist)

那這個呢:

>>> mylist = [u'a',u'b',u'c']
>>> str(tuple(map(str, mylist)))
"('a', 'b', 'c')"

repr()呢?

>>> repr(tuple(mylist))
"(u'a', u'b', u'c')"

有關repr()的更多信息

嘗試這個:

result = "({})".format(",".join(["'{}'".format(char) for char in mylist]))
>>> l = [u'a', u'b', u'c']
>>> str(tuple([str(e) for e in l]))
"('a', 'b', 'c')"

在列表l每個元素e上調用str會將Unicode字符串轉換為原始字符串。 接下來,在列表理解的結果上調用tuple將用括號替換方括號。 最后,對結果進行調用str應該返回元素列表,並用括號將單引號引起來。

這是另一種變化:

mylist = [u'a',u'b',u'c']
result = "\"{0}\"".format(tuple(mylist))
print(result)

輸出:

"('a', 'b', 'c')"    

暫無
暫無

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

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