将字符串转换为长度为1的列表 [英] Convert a string to a list of length one
问题描述
我创建了一个需要列表才能正常工作的方法.但是,您可以发送列表或简单字符串.我想将该字符串转换为包含整个字符串作为元素的列表.例如,如果我有:
I created a method that requires a list in order to work properly. However, you can send in a list OR a simple string. I want to turn that string into a list that contains that entire string as an element. For example, if I have:
"I am a string"
我想将其转换为:
["I am a string"]
我可以这样做:
"I am a string".split("!@#$%^&*")
因为我永远不会有符号的组合,所以它将始终将其转换为列表而不会删除任何字符.但是,这似乎并不是一种很好的方法.还有另一种方法吗?
Because I will never have that combination of symbols, it will always convert it to a list without removing any characters. However, this doesn't seem like that great of a way to do it. Is there another way?
推荐答案
>>> "abc"
'abc'
>>> ["abc"]
['abc']
>>> abc = "abc"
>>> abc
'abc'
>>> [abc]
['abc']
>>> "I am a string".split("!@#$%^&*") == ["I am a string"]
True
将值放在方括号中可以使列表包含一个项目,就像多个值可以使列表中包含多个项目一样.唯一不遵循此模式的容器是元组,因为圆括号也用于分组.在这种情况下,只需在单个项目后添加一个逗号:
Putting the value in square brackets makes a list with one item, just as multiple values makes a list with multiple items. The only container which does not follow this pattern is the tuple, as the round brackets are also used for grouping. In that case, just add a comma after the single item:
>>> abc
'abc'
>>> (abc)
'abc'
>>> (abc,)
('abc',)
如果您希望函数在幕后处理列表和字符串的方式有所不同,请对函数进行编码,例如:
If you want your function to handle list and strings differently under the cover, code your function like:
def f(maybe_list):
if not isinstance(maybe_list, list):
maybe_list = [maybe_list]
# carry on, you have a list.
这篇关于将字符串转换为长度为1的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!