-7

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']
          
Alain Bianchini
  • 3,883
  • 1
  • 7
  • 27
Wilson
  • 11
  • 4

4 Answers4

2

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']
j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

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']

KalebJS
  • 30
  • 7
0

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

sametatila
  • 56
  • 3
-1

Have you tried this How to convert string representation of list to a list? ? Either with json or ast library

plotop
  • 41
  • 4
  • Whilst the link you posted is applicable, it is nice to answer OP's question directly in your answer – Krish Apr 09 '22 at 22:32
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 09 '22 at 22:32