how to replace spaces with commas in a tuple? - python

I need to get a count of the emails received daily in a Gmail mailbox and save that count in a table. To do this I am using the imaplib:
import imaplib
import re
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('xxx#gmail.com', 'password')
obj.select('Inbox')
('OK', ['50'])
gmail_count = obj.search(None,'(SINCE "01-Sep-2020" BEFORE "02-Sep-2020")')
print(gmail_count)
and I get something like this:
('OK', [b'28410 28411 28412 28413 28414 28415 28416 28417 28418 28419 28420 28421 28422 28423 28424 28425 28426 28427 28428 28429 28430 28431 28432 28433 28434 28435 28436 28437 28438 28439'])
I now need to count how many values are in this tuple to get the number of emails so I would like to replace the spaces with commas. How Can I do this?

You can use the replace built-in function to replace spaces by comas in a string
In your case you firstly have to convert your bytes array in a string with the decode("utf-8") function.
If your data are not utf-8 encoded you can change the parameter in the decode function with the correct encoding method.
values = gmail_count[1][0]
replaced = values.decode("utf-8").replace(" ", ",")

You can also just use split to get a list, and then you can get the count and do any other list operations on it:
uidbytes = b’10 20 30’
uidlist = uidbytes.split(b’ ‘)
print(uidlist)
print(len(uidlist))
Output:
[b’10’, b’20, b’30’]
3
You can even change them to integers:
>>> [int(x) for x in uidlist]
[10, 20, 30]

Related

how to print after the keyword from python?

i have following string in python
b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
I want to print the all alphabet next to keyword "name" such that my output should be
waqas
Note the waqas can be changed to any number so i want print any name next to keyword name using string operation or regex?
First you need to decode the string since it is binary b. Then use literal eval to make the dictionary, then you can access by key
>>> s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
>>> import ast
>>> ast.literal_eval(s.decode())['name']
'waqas'
It is likely you should be reading your data into your program in a different manner than you are doing now.
If I assume your data is inside a JSON file, try something like the following, using the built-in json module:
import json
with open(filename) as fp:
data = json.load(fp)
print(data['name'])
if you want a more algorithmic way to extract the value of name:
s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a",\
"persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],\
"name":"waqas"}'
s = s.decode("utf-8")
key = '"name":"'
start = s.find(key) + len(key)
stop = s.find('"', start + 1)
extracted_string = s[start : stop]
print(extracted_string)
output
waqas
You can convert the string into a dictionary with json.loads()
import json
mystring = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
mydict = json.loads(mystring)
print(mydict["name"])
# output 'waqas'
First you need to convert the string into a proper JSON Format by removing b from the string using substring in python suppose you have a variable x :
import json
x = x[1:];
dict = json.loads(x) //convert JSON string into dictionary
print(dict["name"])

how do i create a list when retrieving a list from a dictionary

I am looking up a set of email addresses grouped together in a dictionary using the get() function
the get function returns
['[“one.yahoo.com”,”two.yahoo.com”,"three.yahoo.com"]']
I have tried several methods to remove the single quotes so that I end up with a list like this
email = [ [“one.yahoo.com”,”two.yahoo.com”,"three.yahoo.com"] ]
the dictionary looks like this
dict= { 'Warehouse':'[“x#yahoo.com”,”y#yahoo.com”,”z#yahoo.com”]',
'Bottling':'[“one.yahoo.com”,”two.yahoo.com”,"three.yahoo.com"]'}
Try this:
import ast # This contains a function to convert str to list
email = ['["one.yahoo.com", "two.yahoo.com", "three.yahoo.com"]']
email = str(email) # Converts to str type.
email = email.replace("'", "") # Replaces the apostrophes with blanks.
email = ast.literal_eval(email) # Converts to list.
print(email)
Output is:
[["one.yahoo.com", "two.yahoo.com", "three.yahoo.com"]]
You can try this:
email = ['["one.yahoo.com","two.yahoo.com","three.yahoo.com"]']
email = email[0].replace('"','')
email = email[1:-1].split(",")
Hope this may be of help.

Get list from string with exec in python

I have:
"[15765,22832,15289,15016,15017]"
I want:
[15765,22832,15289,15016,15017]
What should I do to convert this string to list?
P.S. Post was edited without my permission and it lost important part. The type of line that looks like list is 'bytes'. This is not string.
P.S. №2. My initial code was:
import urllib.request, re
f = urllib.request.urlopen("http://www.finam.ru/cache/icharts/icharts.js")
lines = f.readlines()
for line in lines:
m = re.match('var\s+(\w+)\s*=\s*\[\\s*(.+)\s*\]\;', line.decode('windows-1251'))
if m is not None:
varname = m.group(1)
if varname == "aEmitentIds":
aEmitentIds = line #its type is 'bytes', not 'string'
I need to get list from line
line from web page looks like
[15765, 22832, 15289, 15016, 15017]
Assuming s is your string, you can just use split and then cast each number to integer:
s = [int(number) for number in s[1:-1].split(',')]
For detailed information about split function:
Python3 split documentation
What you have is a stringified list. You could use a json parser to parse that information into the corresponding list
import json
test_str = "[15765,22832,15289,15016,15017]"
l = json.loads(test_str) # List that you need.
Or another way to do this would be to use ast
import ast
test_str = "[15765,22832,15289,15016,15017]"
data = ast.literal_eval(test_str)
The result is
[15765, 22832, 15289, 15016, 15017]
To understand why using eval() is bad practice you could refer to this answer
You can also use regex to pull out numeric values from the string as follows:
import re
lst = "[15765,22832,15289,15016,15017]"
lst = [int(number) for number in re.findall('\d+',lst)]
Output of the above code is,
[15765, 22832, 15289, 15016, 15017]

Strip method at Python doesn't clear all

i have some problem to strip '[' at my string (read from file).
code
data = open(Koorpath1,'r')
for x in data:
print(x)
print(x.strip('['))
result
[["0.9986130595207214","26.41608428955078"],["39.44521713256836","250.2412109375"],["112.84327697753906","120.34269714355469"],["260.63800048828125","15.424667358398438"],["273.6199645996094","249.74160766601562"]]
"0.9986130595207214","26.41608428955078"],["39.44521713256836","250.2412109375"],["112.84327697753906","120.34269714355469"],["260.63800048828125","15.424667358398438"],["273.6199645996094","249.74160766601562"]]
Desired output :
"0.9986130595207214","26.41608428955078","39.44521713256836","250.2412109375","112.84327697753906","120.34269714355469","260.63800048828125","15.424667358398438","273.6199645996094","249.74160766601562"
Thanks
It strips the first two '[', it seems you have one long string, you have to split it first.
datalist = data.split[',']
for x in datalist:
# code here
If you don't want to split it and have it all in one string you need replace not strip (strip only works at the end and the beginning.
data = data.replace('[','')
If the data is JSON, then parse it into a Python list and treat it from there:
from itertools import chain
import json
nums = json.loads(x)
print(','.join('"%s"' % num for num in chain.from_iterable(nums)))
chain.from_iterable helps you "flatten" the list of lists and join concatenates everything into one long output.

Remove strings before certain character batch/python [duplicate]

This question already has answers here:
How to get a string after a specific substring?
(9 answers)
Closed 5 years ago.
How can I remove letters before certain character? I need to remove every letter from following string until “[“ character and redirect output to .csv file.
{"__metadata": {"uri": loremipsum etc [ {rest of the document}
As per your provided info and required fields, i will suggest that if your JSON data is in a file then you can use:
import json
data = {}
with open("path to json file") as f:
data = json.loads(f.read())
or if your data is stored in string then you can simply do
data = json.loads("json data string")
now you have data in a python dictionary object. now you can easily get any field from the object e.g getting field "cuid" from the first object in entries list:
print data["entries"][0]["cuid"]
or alternatively you can loop on entries list and get all the fields you need e.g
for entry in data["entries"]:
print entry["cuid"]
print entry["name"]
print entry["id"]
print entry["type"]
Find the position of '[' and get the string after that position
print s[s.find("[")+1:].strip()
Sample output:
{rest of the document}
Hope it helps!
You can split from the first occurence and take the rest like :
>>> string = "Egg[spam:miam"
>>> string.split("[", 1)[1]
>>> spam:miam
OR
>>> string = "Egg[spam:miam"
>>> string[string.index("[") + 1:]
>>> spam:miam

Categories

Resources