What input is imaplib's Internaldate2tuple expecting? - python-3.x

The API reference for Python 3 says imaplib's Internaldate2tuple parses an IMAP4 INTERNALDATE string, yet I can't find the information anywhere what that exactly means. The reverse function (Time2Internaldate) seems to produce one of these INTERNALDATE strings yet it's apparently not good enough for the Internaldate2tuple string. Is this a bug, shouldn't imaplib's functions be compatible with each other?
Is there any other way to parse the internaldate besides regexes and some strftime whatever magic?
from time import localtime
internaldate = imaplib.Time2Internaldate(localtime())
print("Coded: " + internaldate)
coded = imaplib.Internaldate2tuple(internaldate.encode('ascii'))
if coded == None:
print("Wrong format")
else:
print("Success")
internaldate = internaldate.replace('"', '')
print("Coded: " + internaldate)
coded = imaplib.Internaldate2tuple(internaldate.encode('ascii'))
if coded == None:
print("Wrong format")
else:
print("Success")
Output:
Coded: "14-Dec-2019 15:15:47 +0200"
Wrong format
Coded: 14-Dec-2019 15:15:47 +0200
Wrong format

Refer here
A sample input is:
Internaldate2tuple(b'INTERNALDATE "01-Jan-2000 12:00:00 +0000"')

Related

How can I use expression inside formatted string in Nim?

The if expression is not working if used inside of fmt string.
Why, and how to make it work?
import strformat
let v = if true: 1 else: 2 # <= Works
echo fmt"{v}"
echo fmt"{if true: 1 else: 2}" # <= Error
why?
because fmt uses : to separate value of expression from format specifier so (see docs and implementation) the line
echo fmt"{if true: 1 else: 2}"
is expanded by the macro into
var temp = newStringOfCap(educatedCapGuess)
temp.formatValue if true, " 1 else: 2"
temp
which clearly does not compile.
how?
update
currently (April 2021) in devel branch there is a enhancement that allows to use any expression inside a formatted string. For the specific case mentioned you need to surround the expression by parenthesis:
echo fmt"{(if true: 1 else: 2)}"
the new enhancements also allow to use curly brackets in expression (escaping them).
See:
RFC: https://github.com/nim-lang/RFCs/issues/366
a first and a second PR that added the implementation
recent forum discussion: https://forum.nim-lang.org/t/7052
This enhancement will be released for the general public in the next stable version (likely to be 1.6).
old content
I guess it could be seen as a limitation of fmt and I do not think there is currently a way to use an expression with : in fmt where it does not act as a format specificier.
One way to fix this would be to provide an additional formatSpecifierSeparator keyword argument in order to change the default : and be able to do something like:
echo "{if true: 1 else: 2}".fmt('|')
Another way would be to change the implementation of strformatImpl and make sure that the part before a : actually compiles before interpreting : as a formatSpecifier separator.
Both of these ways imply a PR in nim-lang code and would be available after next release or on devel, if accepted and merged.
this works:
import std/strformat
let x = 3.14
assert fmt"{(if x!=0: 1.0/x else: 0):.5}" == "0.31847"
assert fmt"{(if true: 1 else: 2)}" == "1"
assert fmt"{if true\: 1 else\: 2}" == "1"
and avoids conflicts with format specifier. See https://github.com/nim-lang/Nim/pull/17700 for more details.

Importing a created module and printing it

I created a module named smethod.py, which includes this code: (first def to make mixed cased letters lowercase and second to capitalize)
def LWR():
result=""
for i in range(0,len(s)):
value = ord(s[i])
if value>64 and value<91:
result+=chr(value+32)
else:
result+=chr(value)
s=result
print(s)
return
def TTL():
ssplit = s.split()
small_a = ord("a")
small_z = ord("z")
cap_a = ord("A")
delta = small_a - cap_a
for z in ssplit :
if small_a <= ord(z[0]) <= small_z:
l = chr(ord(z[0])-delta)
new = l + z[1:]
print(new, end=" ")
else:
print(s)
return
Then I opened a new file and did this:
import smethod
s = input("Enter your string")
print("The lowercase version is:" ,smethod.LWR)
print("Title version is: ",smethod.TTL)
============= RESTART: /Users/ezgibahadir/Documents/smethod2.py =============
enter your stringezgi bahadır
The lowercase version is: <function LWR at 0x1111b28c0>
Title version is: <function TTL at 0x1111413b0>
What is the reason?
There are many things that could be improved.
You said you called the file method.py, so why are you importing smethod?
Your functions LWR and TTL don't take any arguments. Both of them refer to s, where does that s come from?
Even if they did work, you don't call them. You need to do method.LWR().
You've declared that this is Python3, but you're using the print function like Python2.
Some other issues:
Giving function names as 3-letter capital codes is not the python way. Call them to_lower and to_upper or something instead.
Given that this process is super common, both of these functions are provided in the standard library, you don't even need separate functions.
You could just do:
import smethod
s = input("Enter your string")
print(f"The lowercase version is: {s.lower()}")
print(f"Title version is: {s.upper()}")
In order to recreate the full function with chr and ord, you should be declaring something like:
def to_lower(s):
# code here
return result
And then to call it:
s = 'Hello World!'
print(to_lower(s))

Code not checking if inputted answer is correct

I am trying to create a multiple choice quiz that takes questions from an external .txt file and prints it in python. The text file is laid out like this:
1,Who was the first man to walk on the moon?,A.Michael Jackson,B.Buzz Lightyear,C.Neil Armstrong,D.Nobody,C
When I run the code and input the right answer it still says incorrect but continues to say the answer I inputted.
In the code I split each line in the text file by a ',' so the correct answer in the text file is always detail[6]. In the code I have put:
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I thought this would work as it is checking the inputted answer against detail[6] but it always comes out as incorrect.
import random
score=0
with open('space_quiz_test.txt') as f:
quiz = f.readlines()
questions = random.sample(quiz, 10)
for question in questions:
detail = question.split(",")
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
print(" ")
answer=input("Answer: ")
while True:
if answer.upper() not in ('A','B','C','D'):
print("Answer not valid, try again")
else:
break
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I would like the code to be able to check if the inputted answer is correct by checking it against detail[6] within the text file, instead of always coming out as incorrect, the correct answer is detail[6].
The problem is that readlines() retains the newline character at the end of each line.
Your detail[6] is something like 'C\n' rather than 'C' itself. To fix that, use
detail = question.strip().split(",")

Reversing a string is not matching with the expected output in Python

I have written a python program to reverse the string.
For Example input string is "I am Human" the output will be "namuH ma I"
I have again passed the output to the same function as an input so that the output will be the same string which we have given as input earlier.
Then I am trying to match the given input string to the output but it is not working could you please help.
Program:
def reverse(string):
input_words=string.split(" ")
temp=input_words[::-1]
final=[]
for i in temp:
x=i[::-1]
x=x.strip()
final.append(x)
output=" ".join(final)
return(output)
if __name__ == "__main__":
string="I am Human"
print(reverse(string))
output1=reverse(string)
output2=reverse(output1)
print(string)
print(output2)
output2=output2.strip()
if(output1 == output2):
print("Its maching")
else:
print("\n \n there is some issue please check")
Output:
namuH ma I
I am Human
I am Human
there is some issue please check
You are comparing output1 which "namuH ma I" with output2 which I am Human
So it is not obvious will not match.
One more to notice,you using output2.strip() which will eliminate "whitespace character" on it
Read more at: https://www.tutorialspoint.com/python/string_strip.htm
The output2 variable always have reverse value as output1. So obvious it will not match.
Also there is no use of output2=output2.strip() this line
You might wan't to do like this:
if(string == output2):
print("Its maching")
else:
print("\n \n there is some issue please check")

remove "()" "," and " ' " from a function output..Python3

First off, here's the code. (Still new in function creating)
Function Testing!!
def UserInfo(name, age, birth):
"""Read this by doing UserInfo__doc__"""
print("Name:",name)
print("Age:",age)
print("Birth:",birth)
return
n_input=input("Name?>> ")
a_input=int(input("Age?>> "))
b_input=input("Birth date?(MM DD YYYY)>> ")
UserInfo(n_input, a_input, b_input)
CodeOutput
('name:', 'Jaymz')
('age:', 25)
('birth:', '02 26 1991')
The int portion of the code outputs no " ' " (which I knew) but still with "()" and ","...
The string portion outputs all the stuff I don't want surrounding my output...
How would you get rid of that in your code?(I learn by seeing other code first on how people do it)
ps. Brainfart?.... Do I have to do a "format" on the output code? or is format only for numbers?
you get this output because you're using python 2.x. Python 2 thinks you're printing a tuple. Python 3 would issue what you want.
As jojonas suggested, using from __future__ import print_function also works for all versions. You're not able to use print without parentheses after importing that, which is for the best.
But ...
To treat all cases, use format instead (using {} to indicate the location of the string to insert):
def UserInfo(name, age, birth):
"""Read this by doing UserInfo__doc__"""
print("Name: {}".format(name))
print("Age: {}".format(age))
print("Birth: {}".format(birth))
Note: this also works but is not as powerful:
print("Name: "+name) # would need `str` for integer, ex `str(age)`
print("Name: %s" % name) # old-style formatting

Resources