Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line to check if string or list, then convert to list in Python [duplicate]

Tags:

python

Suppose I have an object a that can either be a string (like 'hello' or 'hello there') or a list (like ['hello', 'goodbye']). I need to check if a is a string or list. If it's a string, then I want to convert it to a one element list (so convert 'hello there' to ['hello there']). If it's a list, then I want to leave it alone as a list.

Is there a Pythonic one-line piece of code to do this? I know I can do:

if isinstance(a, str):
    a = [a]

But I'm wondering if there's a more direct, more Pythonic one-liner to do this.

like image 392
plam Avatar asked Aug 08 '16 05:08

plam


People also ask

How do you check if it is a list or string in Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.

How do you check if a word in a list is in a string Python?

The in Operator It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")

How do you check if a variable is a string or list?

Check if Variable is a List with type() Now, to alter code flow programatically, based on the results of this function: a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.")

How do you turn a string into a list in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


1 Answers

You can use a ternary operator:

a = [a] if isinstance(a, str) else a
like image 85
TigerhawkT3 Avatar answered Oct 22 '22 00:10

TigerhawkT3