The string value
value = "[new=user,pass=h[]@,repalce=que]"
I need the output to be as a list
list = [ "new=user","pass=h[]@","repalce=que" ]
I am new to python just want to know how to deal with these type convertions
The string value
value = "[new=user,pass=h[]@,repalce=que]"
I need the output to be as a list
list = [ "new=user","pass=h[]@","repalce=que" ]
I am new to python just want to know how to deal with these type convertions
You can use the split method as follows:
value = "[new=user,pass=h[]@,repalce=que]"
splitList = value.split(",")
print(splitList)
The split method takes the character that you want to split the sentence on as a parameter.
You can do that in this particular case by the following command
value_list = value[1:-1].split(',')
This way you will first get rid of the brackets (first and last character) and then split by the comma. I do not think there is a more elegant way since this is a rather rare case. I would recommend loading lists as lists or other variables in their correct format and avoid changing the type.
you can use str.split
value = "[new=user,pass=h[]@,repalce=que]"
result = value.split(',')
please note that list
is a type. I recommend not to use it as a variable name.
You could do it using a list comprehension like this:
value = "[new=user,pass=h[]@,repalce=que]"
new_value = [t.replace('pass', 'test') for t in value[1:-1].split(',')]
print(new_value)
Output:
['new=user', 'test=h[]@', 'repalce=que']
Note:
This only works for this particular case.
Also, there's no "type conversion" here
Clean the string thyen convert string to list by string.split()
value = "[new=user,pass=h[]@,repalce=que]"
value = value [1:-1].split(",")
print(value)
output #
['new=user', 'pass=h[]@', 'repalce=que']
I assume the []@
is not supposed to be taken as list. So this is my solution, maybe it would be better to use regex but whatever.
value = "[new=user,pass=h[]@,repalce=que]"
def func(x):
n=len(x)
x=list(x)
s=e=-1
for i in range(0,n-2,1):
if x[i]=='[' and x[i+1]!=']' and x[i+2]!='@':s=i
if x[i]==']' and x[i-1]!='[' and x[i+1]!='@':e=i
x[s]=x[e]=''
x=''.join(x)
x=x.split(',')
return x
print(func(value))
You could split the string
# Python code to convert string to list
def Convert(string):
li = list(string.split(" "))
return li
str1 = "Item1 Item2 Item3"
print(Convert(str1))
Output:
['Item1', 'Item2', 'Item3']