Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中将列表中的一项转换为字符串?_Python_String_List - Fatal编程技术网

如何在Python中将列表中的一项转换为字符串?

如何在Python中将列表中的一项转换为字符串?,python,string,list,Python,String,List,假设我有一张清单: things = ['bananas', 'oranges', 'apples'] 我想把第2项索引1转换成一个字符串,把它存储到另一个变量中 当我试着把它打印出来时,我发现: ['oranges'] 我希望它是一个字符串,而不是列表中的项目 我尝试了str函数,但是Python抛出了一个类型错误。感谢您的帮助 编辑:以下是上下文: def whileremove(x): while(x in scriptlines): new_r = scrip

假设我有一张清单:

things = ['bananas', 'oranges', 'apples']
我想把第2项索引1转换成一个字符串,把它存储到另一个变量中

当我试着把它打印出来时,我发现:

['oranges']
我希望它是一个字符串,而不是列表中的项目

我尝试了str函数,但是Python抛出了一个类型错误。感谢您的帮助

编辑:以下是上下文:

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

我不确定我是否在做与我原来的问题相反的事情,但new\u r.replace不会将new\u r视为字符串。

访问things[1]本身会返回一个字符串,您不必将其更改为字符串。printthings[1]您最终会得到“橙子”。

这应该是相对简单的。要访问第二个元素,可以使用:

things[1]
这将返回字符串“oranges”

要确认这一点,您可以执行以下操作:

things = ['bananas', 'oranges', 'apples']
orange_string = things[1]
print(type(orange_string))
将返回:

<class 'str'>
In[7]:typeothervariable Out[7]:str

在[8]中:其他变量 出[8]:“橙子”


将列表转换为字符串时,访问其元素最终将返回字符串

things = ['bananas', 'oranges', 'apples']
在这里,东西[1]将返回“橙子”
要确认返回类型,只需键入things[1],这将导致

things[1]返回'oranges',这是一个字符串'x'传递给函数的是什么?
things = ['bananas', 'oranges', 'apples']