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
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
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
CodePudding user response:
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']
CodePudding user response:
i assume the []@ is not supposed to be taken as list . so this is my solution ,maybe it would be better to sue 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))
CodePudding user response:
To convert the string to a list, you can use the split() method. This method splits a string into a list of substrings based on a specified delimiter.
For example, you can use the following code to split the string on the , character:
value = "[new=user,pass=h[]@,repalce=que]"
list = value.split(',')
print(list)
This will output will be:
['[new=user', 'pass=h[]@', 'repalce=que]']
If you want to remove the square brackets from the beginning and end of the string, you can use the strip() method to remove them.
value = "[new=user,pass=h[]@,repalce=que]"
list = value.strip('[]').split(',')
print(list)
This will output will be:
['new=user', 'pass=h[]@', 'repalce=que']