Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string into list with one element in python [duplicate]

I have a string which I want to convert to a list with only one element in it.

a = abc print list(a)

output : ['a','b','c']

Expected o/p = ['abc']

What is the proper way to do it ?

like image 770
Naive Avatar asked Jan 11 '17 14:01

Naive


People also ask

How do you convert a string to a list with one element in Python?

Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.

How do you repeat a string in a list Python?

Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list. Here, we just have to keep in mind that to repeat the elements n times, we will have to multiply the list by (n+1).

How do I make a list of one element in Python?

In Python, a list is created by placing elements inside square brackets [] , separated by commas.


1 Answers

Simply use [..]:

a = 'abc'
b = [a]
print(b)

[..] is list notation, you can feed it a comma-separated list of values. For instance [1,4,2,5,'a',1+2,4/3,3.1415],... Or as specified in the documentation:

(..) The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.

like image 54
Willem Van Onsem Avatar answered Sep 28 '22 03:09

Willem Van Onsem