What Is The Right Way To Transform A Python String Into A List? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

What Is The Right Way To Transform A Python String Into A List?

Does placing a string in list would give the output?

20th Jun 2019, 8:17 AM
KEERTHANA PEDDAPYATA
KEERTHANA PEDDAPYATA - avatar
6 Answers
+ 6
#There are 2 simple ways to transform strings into lists: list("PyPy") #["P", "y", "P", "y"] "IronPython".split("o") #["Ir", "nPyth", "n"] #You can also try: [char for char in "Jython"] #["J", "y", "t", "h", "o", "n"] li = [] for char in "Cython": li.append(char) li #["C", "y", "t", "h", "o", "n"]
20th Jun 2019, 8:39 AM
Seb TheS
Seb TheS - avatar
+ 9
Using the split() method str = "Hello World" ls = str.split() print(ls) >>> ["Hello", "World"]
20th Jun 2019, 8:22 AM
Trigger
Trigger - avatar
+ 7
here some samples: >>> lst = list('hello') >>> lst ['h', 'e', 'l', 'l', 'o'] so string is split in it’s individual chars >>> lst = ['hello'] >>> lst ['hello'] string is kept as it is. >>> lst.append('xyz') >>> lst ['hello', 'xyz'] append places string at the end of list >>> lst.insert(0,'world') >>> lst ['world', 'hello', 'xyz'] string 'world' is inserted st index 0 output of lists can be done with : >>> print(lst) ['world', 'hello', 'xyz'] or printed like this: >>> for i in lst: print(i) world hello xyz xyz
20th Jun 2019, 8:28 AM
Lothar
Lothar - avatar
+ 3
Split it and add each element - char OR string 🤗
20th Jun 2019, 10:14 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 3
Ibe Stephen It is not necessary to use the list constructor there, as string.split("-") would already return a list.
20th Jun 2019, 2:52 PM
Seb TheS
Seb TheS - avatar
+ 2
#function to convert the string def Convert(string): li = list(string.split("-")) return li str = "Welcome-Onboard" print(Convert(str)) Output: ['Welcome', 'Onboard']
20th Jun 2019, 2:49 PM
Ibe Stephen
Ibe Stephen - avatar