My question is how to convert a string to a list in Python. When a user enters a string I need to convert it to a list.
user enters => ip1: 1.2
ip2: 3.2
After entering it will becomes "['1.2', '3.2']"
Here is how to convert the above string value to List for looping the values further.
how to get Output => ['1.2','3.2']
CodePudding user response:
Suppose you already have the input in a single multiline text. You can use list comprehension with split
:
user_input = "ip1: 1.2\nip2: 3.2"
output = [line.split(": ")[1] for line in user_input.splitlines()]
print(output) # ['1.2', '3.2']
CodePudding user response:
You're gonna want to use the string library's default .replace
and .split
methods. This can take some tinkering, but you can accomplish this more easily if you know that it will be similarly formatted every time.
For example:
sample_str = "['1.2', '3.2']"
decomposed_str = sample_str.replace("[", "")
decomposed_str = decomposed_str.replace("]", "")
decomposed_str = decomposed_str.replace("'", "")
list = decomposed_str.split(", ")
This will give you the output of ['1.2','3.2']
CodePudding user response:
I think there is a simple solution
user_input = "['1.2', '3.2']"
new_list = eval(user_input)
eval() can change the output type as list
CodePudding user response:
Have you tried this How to convert string representation of list to a list? ? Either with json or ast library