Remove double quotes from a string in python - python-3.x

Would like my output which should not be string but my code returning string to me. Please look on my below code in which z is my output. I tried with regex, replace, strip, eval, ast.literal_eval but nothing worked for me as of now.
x = "'yyyymm'='202005','run_id'='51',drop_columns=run_id"
y = x.split(',')
print(y)
This will print:
["'yyyymm'='202005'","'run_id'='51'","drop_columns=run_id"]`
But I want:
['yyyymm'='202005','run_id'='51',drop_columns=run_id]

x is a string and if you split a string, you will get an array of strings. It is basically cutting it into pieces.
Your question is not really clear on what you want to achieve. If you want to have key-value-pairs, you'd need to split each token at the =. This would give you something like this:
[('yyyymm', '202005'), ('run_id', '51'), ('drop_columns', 'run_id')]
But the items in the tuples would still be strings. If you want to have integers, you would need to cast them which is only possible if the strings consist of digits. It would not be possible to cast 'run_id' to integer.
You can refer to this example. I'm not sure if that is 100% what you are looking for, but it should give you the correct idea.
x = "yyyymm=202005,run_id=51,drop_columns=run_id"
y = x.split(',')
tmp = []
for e in y:
tmp.append((e.split('=')[0], e.split('=')[1]))
out = []
for e in tmp:
if str.isnumeric(e[1]):
out.append((e[0], int(e[1])))
else:
out.append(e)
print(out)
This will give you:
[('yyyymm', 202005), ('run_id', 51), ('drop_columns', 'run_id')]

Related

How to generate a list comprehension with a conditional where the conditional is a NameError

Suppose the following list:
l = ['1','2','M']
How can I transform l to l_1 via a list comprehension?
l_1 = [1, 2, 'M']
I attempted the below without success.
[eval(c) if eval(c) not NameError else c for c in l]
File "<ipython-input-241-7c3f63ffe51b>", line 1
[eval(c) if c not NameError else c for c in list(a)]
^
SyntaxError: invalid syntax
Hi,
You could validate each element of the list l as strings, even if you already have some digits on it such as l = ['1','2','M',3,'p'], that way you have that validation there by passing them all to string and then verifying if the element is digit, and if so, you pass it to int, of float, or number to the new l_1 and if it is not, you simply pass it as string. In this case I will convert each numeric element to int, but you could choose to pass it to number in any other type such as float, for example, if the list contains floating elements.
l = ['1','2','M',3,'p']
l_1 = [int(el) if str(el).isdigit() else el for el in l]
print(l_1)
I certainly hope this helps, good luck and keep coding, it's always fun!
Assuming your general case looks like this, you could use isdigit to only convert numbers.
l=['1','2','M']
l1=[int(c) if c.isdigit() else c for c in l]

Conditional string splitting in Python using regex or loops

I have a string c that has a respective repetitive pattern of:
integer from 0 to 10,
character S, D, or T,
special character * or # (optional)
For instance, c could look like 1D2S#10S, or 1D#2S*3S, or so on.
I have a further calculation to make with c, but in order to do so I thought splitting c into substrings that include integer, character, and a possible special character would be helpful. Hence, for example, 1D2S#10S would be split into 1D, 2S#, 10S. 1D#2S*3S would be split into 1D#, 2S*, 3S.
I am aware that such string split can be concisely done with re.split(), but since this is quite conditional, I wasn't able to find an optimal way to split this. Instead, I tried using a for loop:
clist = []
n = 0
for i in range(len(c)):
if type(c[i]) != 'int':
if type(c[i+1]) == 'int':
clist.append(c[n:i+1])
n = i
else:
clist.append(c[n:i+2])
n = i
This raises an indexing issue, but even despite that I can tell it isn't optimal. Is there a way to use re to split it accordingly?
Use re.findall():
>>> re.findall(r'\d*[SDT][\*#]?', '1D2S#10S')
['1D', '2S#', '10S']
>>> re.findall(r'\d*[SDT][\*#]?', '1D#2S*3S')
['1D#', '2S*', '3S']

why doesn't this regex (\d)\d\1 work to find alternate repetitive numbers from a string?

I have to write regex to find all the repetitive alternate numbers from a given string.
For example:
552523
(5,5)and(2,2) are the pairs
My basic understanding of regex is not very good.
From what I understand the expression (\d)\d\1 should give 525 and 252 but it only returns 5 while using re.findall function in python.
Why doesn't this work? And is there a good way to accomplish this?
You can perform the overlapping match by using the lookahead assertion.
Would you please try the following:
import re
str = "552523"
m = re.finditer(r'(?=((\d)\d\2))', str)
for i in m:
print(i.group(1))
Output:
525
252
Another way to come at it would be to zip over the string and a slice of the string offset by 2 looking for matching digits in the resulting tuples.
Example:
digit_string = "552523"
digit_pairs = [
(x, y)
for x, y in zip(digit_string, digit_string[2:])
if x.isdigit() and y.isdigit() and x == y
]
print(digit_pairs)
Output:
[('5', '5'), ('2', '2')]

How can i optimise my code and make it readable?

The task is:
User enters a number, you take 1 number from the left, one from the right and sum it. Then you take the rest of this number and sum every digit in it. then you get two answers. You have to sort them from biggest to lowest and make them into a one solid number. I solved it, but i don't like how it looks like. i mean the task is pretty simple but my code looks like trash. Maybe i should use some more built-in functions and libraries. If so, could you please advise me some? Thank you
a = int(input())
b = [int(i) for i in str(a)]
closesum = 0
d = []
e = ""
farsum = b[0] + b[-1]
print(farsum)
b.pop(0)
b.pop(-1)
print(b)
for i in b:
closesum += i
print(closesum)
d.append(int(closesum))
d.append(int(farsum))
print(d)
for i in sorted(d, reverse = True):
e += str(i)
print(int(e))
input()
You can use reduce
from functools import reduce
a = [0,1,2,3,4,5,6,7,8,9]
print(reduce(lambda x, y: x + y, a))
# 45
and you can just pass in a shortened list instead of poping elements: b[1:-1]
The first two lines:
str_input = input() # input will always read strings
num_list = [int(i) for i in str_input]
the for loop at the end is useless and there is no need to sort only 2 elements. You can just use a simple if..else condition to print what you want.
You don't need a loop to sum a slice of a list. You can also use join to concatenate a list of strings without looping. This implementation converts to string before sorting (the result would be the same). You could convert to string after sorting using map(str,...)
farsum = b[0] + b[-1]
closesum = sum(b[1:-2])
"".join(sorted((str(farsum),str(closesum)),reverse=True))

Switching positions of two strings within a list

I have another question that I'd like input on, of course no direct answers just something to point me in the right direction!
I have a string of numbers ex. 1234567890 and I want 1 & 0 to change places (0 and 9) and for '2345' & '6789' to change places. For a final result of '0678923451'.
First things I did was convert the string into a list with:
ex. original = '1234567890'
original = list(original)
original = ['0', '1', '2' etc....]
Now, I get you need to pull the first and last out, so I assigned
x = original[0]
and
y = original[9]
So: x, y = y, x (which gets me the result I'm looking for)
But how do I input that back into the original list?
Thanks!
The fact that you 'pulled' the data from the list in variables x and y doesn't help at all, since those variables have no connection anymore with the items from the list. But why don't you swap them directly:
original[0], original[9] = original[9], original[0]
You can use the slicing operator in a similar manner to swap the inner parts of the list.
But, there is no need to create a list from the original string. Instead, you can use the slicing operator to achieve the result you want. Note that you cannot swap the string elements as you did with lists, since in Python strings are immutable. However, you can do the following:
>>> a = "1234567890"
>>> a[9] + a[5:9] + a[1:5] + a[0]
'0678923451'
>>>

Resources