Converting a string to list through python - python

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

Related

how to split string and assign it to arey with adding some parts in python

I have some string which contains parts separated by commas and need to add some part to each and assign all to array of variables.
the string looks like
chp_algos = 'AES256_SSE','AES128_CBC','AES64_CBC','AES33_CBC'
I want to put in array which looks like:
arr = [
[AES128_CBC],
[AES128_CBC_fer],
[AES128_SSE],
[AES128_SSE_fer],
[AES64_CBC],
[AES64_CBC_fer],
[AES33_CBC],
[AES33_CBC_fer]
]
and I want to map the following final result to db
f = 'AES128_CBC_fer AES128_SSE_fer AES64_CBC_fer AES33_CBC_fer'
As written in the question, chp_algos is a tuple, not a string. So, it is already "split"
I'd recommend not using a list of lists. Just create a list of strings.
from itertools import chain
arr = list(chain.from_iterable([x, x + '_fer'] for x in chp_algos))
Output
['AES256_SSE',
'AES256_SSE_fer',
'AES128_CBC',
'AES128_CBC_fer',
'AES64_CBC',
'AES64_CBC_fer',
'AES33_CBC',
'AES33_CBC_fer']
With that, you can filter.
But you could also just skip arr and build a new list from concatenating to the original string values
f = ' '.join(x for x in arr if x.endswith('_fer'))
You can do this by sorting chp_algos then using f strings in a generator expression
>>> ' '.join(f'{i}_fer' for i in sorted(chp_algos))
'AES128_CBC_fer AES256_SSE_fer AES33_CBC_fer AES64_CBC_fer'
Could you clarify your string chp_algos? The way you wrote it now it is not compatible with python.
Anyway, what you can do in your case, assuming that chp_algos is a string of the form chp_algos= "'AES256_SSE','AES128_CBC','AES64_CBC','AES33_CBC'", then you can split the string into a list of strings via chp_algos.split(",").
The argument of split() is the delimiter which should be used to split the string.
Now you have something like array = ["'AES256_SSE'", "'AES128_CBC'", "'AES64_CBC'", "'AES33_CBC'"].
To get the array that you want you can just do a simple loop through your array:
arr = []
for element in array:
arr.append([element])
arr.append([element + str("_fer")])
Now you might have some issues with the quotes (depends on how your data looks like). But these you can just remove by looking at the relevant indices of element. To do this just replace element in the code above by element[1:-2]. This removes the first and the last element of the string.
To get the f string in the very end, you can just loop through arr[1::2] which returns every 2nd element of arr starting at the second one (index 1).
Say we have a string:
s = 'AES256_SSE,AES128_CBC,AES64_CBC,AES33_CBC'
In order to replace commas with a space and append a suffix to each part:
' '.join(f'{p}_fer' for p in s.split(','))
As for an array:
def g(s):
for s in s.split(','):
yield s
yield f'{s}_fer'
arr = [*g(s)]

How do I replace certain pieces in a string in a list in python?

['Parent=transcript:Zm00001d034962_T001', 'Parent=transcript:Zm00001d034962_T002', 'Parent=transcript:Zm00001d034962_T003', 'Parent=transcript:Zm00001d034962_T003', 'Parent=transcript:Zm00001d034962_T004', 'Parent=transcript:Zm00001d034962_T005', 'Parent=transcript:Zm00001d034962_T005', 'Parent=transcript:Zm00001d034962_T005']
This is what it looks like.
I would like to replace Parent=transcript: and _T00
please help. not sure what command to use
Use python's built-in replace() function. For the last part, if it's always 5 characters you can easily exclude them:
items = [
'Parent=transcript:Zm00001d034962_T001',
'Parent=transcript:Zm00001d034962_T002',
'Parent=transcript:Zm00001d034962_T003',
'Parent=transcript:Zm00001d034962_T003',
'Parent=transcript:Zm00001d034962_T004',
'Parent=transcript:Zm00001d034962_T005',
'Parent=transcript:Zm00001d034962_T005',
'Parent=transcript:Zm00001d034962_T005'
]
# use enumerate to replace the item in the list
for index, item in enumerate(items):
# this replaces the items with an empty string, deleting it
new_item = item.replace('Parent=transcript:', '')
# this accesses all the characters in the string minus the last 5
new_item = new_item[0:len(new_item) - 5] + "whatever you want to replace that with"
# replace the item in the list
items[index] = new_item
I am assuming you want to replace the following strings to ''
Replace Parent=transcript: to ''
Replace _T00 to ''
For example,
'Parent=transcript:Zm00001d034962_T001' will get replaced as 'Zm00001d0349621'.
The ending string 1 from _T001 will get concatenated to Zm00001d034962.
If that is your expected result, the code is:
new_list = [x.replace('Parent=transcript:','').replace('_T00','') for x in input_list]
print (new_list)
The output of new_list will be:
['Zm00001d0349621', 'Zm00001d0349622', 'Zm00001d0349623', 'Zm00001d0349623', 'Zm00001d0349624', 'Zm00001d0349625', 'Zm00001d0349625', 'Zm00001d0349625']
Note you can replace '' with whatever you want the new string to be. I have marked it as '' as I don't know what your new replaced string will be.

How to remove characters from a string after a certain point within a list?

I have a list of strings within a list and I want to remove everything in each string after the tenth character.
EX:
['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']
I want just the first ten integers from the list and everything else should be stripped from it.
Output
['0.04112243', '0.12733313', '0.09203131']
You can use a list comprehension:
original = ['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']
new = [s[:10] for s in original]
Output:
['0.04112243', '0.12733313', '0.09203131']
You can also be a bit more flexible if you want to keep everything before the first comma:
new = [s.partition(',')[0] for s in original]
You can access string characters similar as an array.
Code:
example = ['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']
for s in example:
print(s[:10])
Output:
0.04112243
0.12733313
0.09203131
list comprehension and string slicing:
dirty = ['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']
clean = [num[:10] for num in dirty]
Split() creates a list of strings delimited by the specified character. With this in mind, I would split each string on the comma (,) char and then append the first element to a list.
lst = ['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']
result = []
for i in lst:
result.append(i.split(",")[0])
#Test output
print(result)
This should return the values you need, in the format you want!
Hope this helps.

String Division in Python

I have a list of strings that all follow a format of parts of the name divided by underscores. Here is the format:
string="somethingX_somethingY_one_two"
What I want to know how to do it extract "one_two" from each string in the list and rebuild the list so that each entry only has "somethingX_somethingY". I know that in C, there is a strtok function that is useful for splitting into tokens, but I'm not sure if there is a method like that or a strategy to get that same effect in Python. Help me please?
You can use split and a list comprehension:
l = ['_'.join(s.split('_')[:2]) for s in l]
If you're literally trying to remove "_one_two" from the end of the strings, then you can do this:
tail_len = len("_one_two")
strs = [s[:-tail_len] for s in strs]
If you want to remove the last two underscore-separated components, then you can do this:
strs = ["_".join(s.split("_")[:-2]) for s in strs]
If neither of these is what you want, then let update the question with more details.
I think this does what you're asking for.
s = "somethingX_somethingY_one_two"
splitted = s.split( "_" )
splitted = [ x for x in splitted if "something" in x ]
print "_".join( splitted )

parsing in python

I have following string
adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0
I need only the value of adId,siteId and userId.
means
4028cb901dd9720a011e1160afbc01a3
8a8ee4f720e6beb70120e6d8e08b0002
5082a05c-015e-4266-9874-5dc6262da3e0
all the 3 in different variable or in a array so that i can use all three
You can split them to a dictionary if you don't need any fancy parsing:
In [2]: dict(kvpair.split(':') for kvpair in s.split(';'))
Out[2]:
{'adId': '4028cb901dd9720a011e1160afbc01a3',
'siteId': '8a8ee4f720e6beb70120e6d8e08b0002',
'userId': '5082a05c-015e-4266-9874-5dc6262da3e0'}
You could do something like this:
input='adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0'
result={}
for pair in input.split(';'):
(key,value) = pair.split(':')
result[key] = value
print result['adId']
print result['siteId']
print result['userId']
matches = re.findall("([a-z0-9A-Z_]+):([a-zA-Z0-9\-]+);", buf)
for m in matches:
#m[1] is adid and things
#m[2] is the long string.
You can also limit the lengths using {32} like
([a-zA-Z0-9]+){32};
Regular expressions allow you to validate the string and split it into component parts.
There is an awesome method called split() for python that will work nicely for you. I would suggest using it twice, once for ';' then again for each one of those using ':'.

Categories

Resources