python - Convert a string to a list of length one -
i created method requires list in order work properly. however, can send in list or simple string. want turn string list contains entire string element. example, if have:
"i string" i want convert to:
["i string"] i able so:
"i string".split("!@#$%^&*") because never have combination of symbols, convert list without removing characters. however, doesn't seem great of way it. there way?
>>> "abc" 'abc' >>> ["abc"] ['abc'] >>> abc = "abc" >>> abc 'abc' >>> [abc] ['abc'] >>> "i string".split("!@#$%^&*") == ["i string"] true putting value in square brackets makes list 1 item, multiple values makes list multiple items. container not follow pattern tuple, round brackets used grouping. in case, add comma after single item:
>>> abc 'abc' >>> (abc) 'abc' >>> (abc,) ('abc',) if want function handle list , strings differently under cover, code function like:
def f(maybe_list): if not isinstance(maybe_list, list): maybe_list = [maybe_list] # carry on, have list.
Comments
Post a Comment