Important !!! - Do not name your python script the same as the module being imported!!! e.g. if you want to import "calendar" module, do not name you script as calendar.py ... it will import your script instead.
Return an iterator for the week day numbers that will be used for one week
itermonthdates(year, month)
Return an iterator for the month month (1–12) in the year year.
itermonthdays(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will simply be day of the month numbers. For the days outside of the specified month, the day number is 0.
itermonthdays2(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a day of the month number and a week day number.
itermonthdays3(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.
itermonthdays4(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.
monthdatescalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.
monthdays2calendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers.
monthdayscalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.
yeardatescalendar(year, width=3)
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are datetime.date objects.
yeardays2calendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero.
yeardayscalendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.
This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers, dict,
list, set, and tuple.
namedtuple
factory function for creating tuple subclasses with named fields
deque
list-like container with fast appends and pops on either end
.append(..)
.appendleft(..)
.clear(..)
.copy(..)
.count(..)
.extend(..)
.extendleft(..)
.index(..)
.insert(..)
.pop(..)
.popleft(..)
.remove(..)
reverse(..)
.rotate(..)
ChainMap
dict-like class for creating a single view of multiple mappings
Counter
dict subclass for counting hashable objects
OrderedDict
dict subclass that remembers the order entries were added
defaultdict
dict subclass that calls a factory function to supply missing values
UserDict
wrapper around dictionary objects for easier dict subclassing
UserList
wrapper around list objects for easier list subclassing
UserString
wrapper around string objects for easier string subclassing
namedtuple example 2
>>> from collections import namedtuple
>>> Car = namedtuple('Car','Price Mileage Colour Class')
>>> xyz = Car(Price = 100000, Mileage = 30, Colour = 'Cyan', Class = 'Y')
>>> print xyz
Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y')
>>> print xyz.Class
Y
namedtuple example 3
#input line 1 N = no. of students
#input line 2 = column headings that include MARKS
#next N lines, columns of data for each headingfrom collections import namedtuple
N = int(input())
Student = namedtuple('Student',input().split())
print(sum([ int(Student._make(input().split()).MARKS) for i in range(N) ]) / N)
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d['python'].append("awesome")
>>> d['something-else'].append("not relevant")
>>> d['python'].append("language")
>>> for i in d.items():
print i
('python', ['awesome', 'language'])
('something-else', ['not relevant'])
explanation: when d['python'] was first used, there was no item in the dictionary with key='python', but because default factory was set as list, it will call list() to assign empty list to d['python'] and then allow it to call the append method (which is available to list data type] to
add items to that list value.
OrderedDict example
from collections import OrderedDict
N = int(input())
inventory = OrderedDict()
for i in range(N) :
itemlist = input().split()
item_name = ' '.join(itemlist[:-1])
price = int(itemlist[-1])
try:
inventory[item_name] += price
except:
inventory[item_name] = price
for item,price in inventory.items():
print(item,price)
Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its __next__() method is called — file objects and list objects are both suitable
csv.writer(csvfile, dialect='excel', **fmtparams)
Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method
class csv.DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
Create an object that operates like a regular reader but maps the information in each row to a dict whose keys are given by the optional fieldnames parameter
class csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
Create an object which operates like a regular writer but maps dictionaries onto output rows
Example - csv.reader
>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
>>> import csv
>>> with open('names.csv', newline='') as csvfile:
... reader = csv.DictReader(csvfile)
... for row in reader:
... print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese
Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).
If recursive is true, the pattern “**” will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match.
Note
Using the “**” pattern in large directory trees may consume an inordinate amount of time.
Changed in version 3.5: Support for recursive globs using “**”.
glob.iglob(pathname, *, recursive=False)
Return an iterator which yields the same values as glob() without actually storing them all simultaneously.
glob.escape (pathname)
Escape all special characters ('?', '*' and '['). This is useful if you want to match an arbitrary literal string that may have special characters in it. Special characters in drive/UNC sharepoints are not escaped, e.g. on Windows escape('//?/c:/Quovadis?.txt') returns '//?/c:/Quovadis[?].txt'.
- enter K rows of List of Integers of variable length
- find all posible combination of K integers taking 1 item each from each list
import itertools
K = int(input())
LoL = []
for i in range(K):
Li = list(map(int,input().split()))
LoL.append(Li) print(LoL)
for C in itertools.product(*LoL):
print("combination: {0}".format(C))
degrees(x, /)
Convert angle x from radians to degrees.
erf(x, /)
Error function at x.
erfc(x, /)
Complementary error function at x.
exp(x, /)
Return e raised to the power of x.
expm1(x, /)
Return exp(x)-1.
fabs(x, /)
Return the absolute value of the float x.
factorial(x, /)
Find x!.
Raise a ValueError if x is negative or non-integral.
floor(x, /)
Return the floor of x as an Integral.
This is the largest integer <= x.
fmod(x, y, /)
Return fmod(x, y), according to platform C.
x % y may differ.
frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.
Assumes IEEE-754 floating point arithmetic.
gamma(x, /)
Gamma function at x.
gcd(x, y, /)
greatest common divisor of x and y
hypot(x, y, /)
Return the Euclidean distance, sqrt(x*x + y*y).
isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Determine whether two floating point numbers are close in value.
rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values
Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.
isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.
ldexp(x, i, /)
Return x * (2**i).
This is essentially the inverse of frexp().
lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
log10(x, /)
Return the base 10 logarithm of x.
log1p(x, /)
Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero.
log2(x, /)
Return the base 2 logarithm of x.
modf(x, /)
Return the fractional and integer parts of x.
Both results carry the sign of x and are floats.
pow(x, y, /)
Return x**y (x to the power of y).
radians(x, /)
Convert angle x from degrees to radians.
remainder(x, y, /)
Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.
sin(x, /)
Return the sine of x (measured in radians).
sinh(x, /)
Return the hyperbolic sine of x.
sqrt(x, /)
Return the square root of x.
tan(x, /)
Return the tangent of x (measured in radians).
tanh(x, /)
Return the hyperbolic tangent of x.
trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.
Eg. - os.listdir : list files and then rename to specific format
find files that match "p (n).jpg" and rename to "p00n.jpg"
import os
import re
for f in os.listdir():
m = re.match(r'(p) [(]([0-9]+)[)](.jpg)',f)
if m is not None:
nf = "{}{:03d}{}".format(m.group(1),int(m.group(2)),m.group(3))
os.rename(f,nf)
Eg. - os.environ : Append a path to existing PATH env variable
special characters: . Matches any character except a newline. ^ Matches the start of the string. $ Matches the end of the string or just before the newline at
the end of the string. * Matches 0 or more (greedy) repetitions of the preceding RE. *? Matches 0 or more (non-greedy) repetitions of the preceding RE. + Matches 1 or more (greedy) repetitions of the preceding RE. +? Matches 1 or more (non-greedy) repetitions of the preceding RE. ? Matches 0 or 1 (greedy) of the preceding RE. ?? Matches 0 or 1 (non-greedy) of the preceding RE. {m,n} Matches from m to n repetitions (greedy) of the preceding RE. {m,n}? Matches from m to n repetitions (non-greedy) of the preceding RE.
Greedy means that it will match as many repetitions as possible. Non-Greedy means that it will match as few repetitions as possible.
\ Either escapes special characters or signals a special sequence. [] Indicates a set of characters. A "^" as the first character
after "[" indicates a complementing set. | A|B, creates an RE that will match either A or B. () Matches the RE inside the parentheses.
The contents can be retrieved or matched later in the string. (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below). (?:...) Non-grouping/capturing version of regular parentheses.
e.g. (?:apple|orange|banana) will match either apple or orange or banana but will not capture
the string into the capture group.
(?P<name>...) The substring matched by the group is accessible by name. (?P=name) Matches the text matched earlier by the group named name. (?#...) A comment; ignored.
Lookarounds - lookahead and lookbehind (?=...) Matches if ... matches next, but doesn't consume the string. (Positive lookahead) >>> re.findall(r'(1)(?=2)','123456') ['1']
>>> # finds 3 digit sequence where 2nd digit IS 2 >>> re.findall(r'(\d(?=2)\d\d)','121456') ['121'] (?!...) Matches if ... doesn't match next. (Negative lookahead) >>> # find 3 digit sequence where 2nd digit is NOT 2 >>> re.findall(r'(1)(?!2)','123456') []
(?<=...) Matches if preceded by ... (must be fixed length). (Positive lookbehind)
(?<!...) Matches if not preceded by ... (must be fixed length). (Negative lookbehind)
(?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
the (optional) no pattern otherwise.
\A Matches only at the start of the string. \Z Matches only at the end of the string. \b Matches the empty string, but only at the start or end of a word. \B Matches the empty string, but not at the start or end of a word. \d Matches any decimal digit; equivalent to the set [0-9] in
bytes patterns or string patterns with the ASCII flag.
In string patterns without the ASCII flag, it will match the whole
range of Unicode digits. \D Matches any non-digit character; equivalent to [^\d]. \s Matches any whitespace character; equivalent to [ \t\n\r\f\v] in
bytes patterns or string patterns with the ASCII flag.
In string patterns without the ASCII flag, it will match the whole
range of Unicode whitespace characters. \S Matches any non-whitespace character; equivalent to [^\s]. \w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]
in bytes patterns or string patterns with the ASCII flag.
In string patterns without the ASCII flag, it will match the
range of Unicode alphanumeric characters (letters plus digits
plus underscore).
With LOCALE, it will match the set [0-9_] plus characters defined
as letters for the current locale. \W Matches the complement of \w. \ Matches a literal backslash.
Compile a regular expression pattern string, returning a Pattern object.
example
import re
regexes = [ re.compile(p) for p in ['[a-zA-Z]+','[0-9]+','[!@#$%&-+]+'] ]
text = "This contain alphabets and numbers 123 but no symbols"
for regex in regexes:
print("search for {0:10s}\t{1}".format(regex.pattern,text))
if regex.search(text):
print("=> Match")
else:
print("=> No match")
sample run
search for [a-zA-Z]+ This contain alphabets and numbers 123 but no symbols => Match
search for [0-9]+ This contain alphabets and numbers 123 but no symbols => Match
search for [!@#$%&-+]+ This contain alphabets and numbers 123 but no symbols => No match
re.escape(pattern)
Escape special characters in a string.
example
>>> import re
>>> print(re.escape('http://www.python.org'))
http://www\.python\.org
re.findall(pattern, string, flags=0)
Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.
re.findall examples - extract repeating character or number sequences
>>> import re >>> print([x[0] for x in re.findall(r'((.)*)', 'abbcccddddcccbba')])
['a', 'bb', 'ccc', 'dddd', 'ccc', 'bb', 'a']
>>> print([x[0] for x in re.findall(r'((\d)*)', '1233-4444-5543-2121')])
['1', '2', '33', '4444', '55', '4', '3', '2', '1', '2', '1']
Return an iterator over all non-overlapping matches in the string. For each match, the iterator returns a Match object. Empty matches are included in the result.
example
>>> text = "He was carefully disguised but captured quickly by police."
>>> for m in re.finditer(r"\w+ly", text):
... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0)))
07-16: carefully
40-47: quickly
re.fullmatch(pattern, string, flags=0)
Try to apply the pattern to all of the string, returning a Match object, or None if no match was found.
example
>>> S="This is my ip address 123.123.123.123"
>>> T="This is my ip address 123.123.123.123 and other stuff"
>>> if re.fullmatch('This.*123',S) is not None:
... print("Matched")
... else:
... print("Not matched")
...
Matched
>>> if re.fullmatch('This.*123',T) is not None:
... print("Matched")
... else:
... print("Not matched")
...
Not matched
re.match(pattern, string, flags=0)
Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.
example 1
>>> S="This is my ip address 123.123.123.123"
>>> T="This is my ip address 123.123.123.123 and other stuff"
>>> if re.match("This.*123",S) is not None:
... print("Matched")
... else:
... print("Not matched")
...
Matched
>>> if re.match('This.*123',T) is not None:
... print("Matched")
... else:
... print("Not matched")
...
Matched
Note: both strings matched, because re.match checks for the pattern only at the start of the string
re.purge()
Clear the regular expression caches
re.search(pattern, string, flags=0)
Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found.
example 1
>>> import re
>>> m = re.search(r'(\w+)@(\w+)\.(\w+)','username@example.com')
>>> m.groups()
('username', 'example', 'com')
example 2
>>> import re >>> m = re.search(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','myname@example.com')
>>> m.groupdict()
{'website': 'example', 'user': 'myname', 'extension': 'com'}
example 3
>>> import re >>> m = re.search(r'(\w+)@(\w+)\.(\w+)','username@example.com') >>> m.group(0) # The entire match 'username@example.com' >>> m.group(1) # The first parenthesized subgroup. 'username' >>> m.group(2) # The second parenthesized subgroup. 'example' >>> m.group(3) # The third parenthesized subgroup. 'com' >>> m.group(1,2,3) # Multiple arguments give us a tuple. ('username', 'example', 'com')
re.split(pattern, string, maxsplit=0, flags=0)
Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.
examples
- following example will split by ',' or '.'
import re
print("\n".join(re.split('[.,]',input())))
or
import re
regex_pattern = r"[,.]"
print("\n".join(re.split(regex_pattern, input())))
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string
or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the Match object and must return a replacement string to be used.
example(s)
>>> import re
>>> S='1 two 3'
>>> R = re.sub(' two ','2',S)
>>> R
'123'
>>> import re
>>> S=' SeP 2018 (ABC).docx'
>>> R = re.sub('^\s+[Ss][Ee][Pp]\s+\d+\s','',S)
>>> R
'(ABC).docx'
# replace all commas (,) within double quotes
>>> import re
>>> s = 'abc,def,"ghi,jkl,mno",pqr,stu'
>>> re.sub(r'"[^"]+"', lambda x: x.group().replace(',', '|'), s)
'abc,def,"ghi|jkl|mno",pqr,stu'
re.subn(pattern, repl, string, count=0, flags=0)
Return a 2-tuple containing (new_string, number). new_string is the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in the source string by the replacement repl. number is the number of substitutions that were made. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the Match object and must return a replacement string to be used.
example
>>> import re
>>> S="yearly, monthly, weekly, daily"
>>> T=re.subn("ly","LY",S)
>>> T
('yearLY, monthLY, weekLY, daiLY', 4)
re.template(pattern, flags=0)
Compile a template pattern, returning a Pattern object
re.A|re.ASCII
Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a)
re.I|re.IGNORECASE
Perform case-insensitive matching; expressions like [A-Z] will also match lowercase letters. Full Unicode matching (such as Ü matching ü) also works unless the re.ASCII flag is used to disable non-ASCII matches. The current locale does not change the effect of this flag unless the re.LOCALE flag is also used. Corresponds to the inline flag (?i)
re.L|re.LOCALE
Make \w, \W, \b, \B and case-insensitive matching dependent on the current locale. This flag can be used only with bytes patterns. The use of this flag is discouraged as the locale mechanism is very unreliable, it only handles one “culture” at a time, and it only works with 8-bit locales. Unicode matching is already enabled by default in Python 3 for Unicode (str) patterns, and it is able to handle different locales/languages. Corresponds to the inline flag (?L)
re.M|re.MULTILINE
When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character '$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string. Corresponds to the inline flag (?m)
re.S|re.DOTALL
Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline. Corresponds to the inline flag (?s)
re.X|re.VERBOSE
This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like *?, (?: or (?P<...>. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored
## e.g. use re.IGNORECASE to enable case Insensitive search
>>> import re
>>> string="PYTHon"
>>> m=re.search(r"thon",string,re.IGNORECASE)
>>> m
<re.Match object; span=(2, 6), match='THon'>
>>> import os,subprocess >>> my_env = os.environ.copy()
... # can edit or change my_env here >>> subprocess.run(["env"],env=my_env)
Classes
subprocess.completedProcess
args
The arguments used to launch the process. This may be a list or a string.
returncode
Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully. A negative value -N indicates that the child was terminated by signal N (POSIX only).
stdout
Captured stdout from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stdout was not captured.
If you ran the process with stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, and stderr will be None.
stderr
Captured stderr from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stderr was not captured.
Method called immediately after the test method has been called and the result recorded.
setUpClass()
A class method called before tests in an individual class are run.
tearDownClass()
A class method called after tests in an individual class have run.
run(result=None)
Run the test, collecting the result into the TestResult object passed as result.
skipTest(reason)
Calling this during a test method or setUp() skips the current test.
debug()
Run the test without collecting the result. This allows exceptions raised by the test to be propagated to the caller, and can be used to support running tests under a debugger.
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)