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.
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.
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!")
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.")
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.
You can use a ternary operator:
a = [a] if isinstance(a, str) else a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With