简体   繁体   English

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

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

So, imagine I have a list Things:所以,想象一下我有一个清单:

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

And I want to convert item 2 (index 1) into a string to store it into another variable.我想将项目 2(索引 1)转换为字符串以将其存储到另一个变量中。

When I try to just print it out, I get this:当我尝试将其打印出来时,我得到了这个:

['oranges']

I want this to be a string instead of an item in a list.我希望这是一个字符串而不是列表中的一个项目。

I've tried the str() function, but Python spits out a TypeError.我已经尝试过 str() 函数,但是 Python 吐出一个 TypeError。 Any help is appreciated!任何帮助表示赞赏!

Edit: Here's the context:编辑:这是上下文:

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

I'm not sure if I'm doing something contrary to my original question, but new_r.replace doesn't treat new_r as a string.我不确定我是否在做与我原来的问题相反的事情,但 new_r.replace 不会将 new_r 视为字符串。

Accessing things[1] is itself returns a string you don't have to change this to string.访问事物 [1] 本身会返回一个字符串,您不必将其更改为字符串。 print(things[1]) you will eventually get 'oranges'. print(things[1])你最终会得到“橙子”。

This should be relatively straight forward.这应该是相对简单的。 To access the second element you can use:要访问第二个元素,您可以使用:

things[1]

This will return the string 'oranges'.这将返回字符串“oranges”。

To confirm this you can do the following:要确认这一点,您可以执行以下操作:

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

Which will return:哪个将返回:

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

In [7]: type(othervariable)在 [7] 中:类型(其他变量)
Out[7]: str出[7]:str

In [8]: othervariable在 [8] 中:其他变量
Out[8]: 'oranges'出[8]:'橘子'

??? ???

While converting a list to a string, accessing its elements will eventually return a String.将列表转换为字符串时,访问其元素最终将返回一个字符串。

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

Here, things[1] will return 'oranges' To confirm the return type, just type(things[1]), this results in <class 'str'>这里,things[1] 将返回 'oranges' 要确认返回类型,只需键入(things[1]),这将导致 <class 'str'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM