+ 7
What Is The Right Way To Transform A Python String Into A List?
Does placing a string in list would give the output?
7 Antworten
+ 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"]
+ 9
Using the split() method
str = "Hello World"
ls = str.split()
print(ls)
>>> ["Hello", "World"]
+ 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
+ 3
Split it and add each element - char OR string 🤗
+ 3
Ibe Stephen It is not necessary to use the list constructor there, as string.split("-") would already return a list.
+ 2
#function to convert the string
def Convert(string):
li = list(string.split("-"))
return li
str = "Welcome-Onboard"
print(Convert(str))
Output:
['Welcome', 'Onboard']