簡體   English   中英

如何將列表中的一項轉換為 Python 中的字符串?

[英]How do I convert one item of a list into a string in Python?

所以,想象一下我有一個清單:

things = ['bananas', 'oranges', 'apples']

我想將項目 2(索引 1)轉換為字符串以將其存儲到另一個變量中。

當我嘗試將其打印出來時,我得到了這個:

['oranges']

我希望這是一個字符串而不是列表中的一個項目。

我已經嘗試過 str() 函數,但是 Python 吐出一個 TypeError。 任何幫助表示贊賞!

編輯:這是上下文:

def whileremove(x):
    while(x in scriptlines):
        new_r = scriptlines[x]
        new_r = new_r.replace(x, "")

我不確定我是否在做與我原來的問題相反的事情,但 new_r.replace 不會將 new_r 視為字符串。

訪問事物 [1] 本身會返回一個字符串,您不必將其更改為字符串。 print(things[1])你最終會得到“橙子”。

這應該是相對簡單的。 要訪問第二個元素,您可以使用:

things[1]

這將返回字符串“oranges”。

要確認這一點,您可以執行以下操作:

things = ['bananas', 'oranges', 'apples']
orange_string = things[1]
print(type(orange_string))

哪個將返回:

<class 'str'>
things = ['bananas', 'oranges', 'apples'] 
othervariable = str(things[1]) 

在 [7] 中:類型(其他變量)
出[7]:str

在 [8] 中:其他變量
出[8]:'橘子'

???

將列表轉換為字符串時,訪問其元素最終將返回一個字符串。

things = ['bananas', 'oranges', 'apples']

這里,things[1] 將返回 'oranges' 要確認返回類型,只需鍵入(things[1]),這將導致 <class 'str'>

暫無
暫無

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

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