Professional Documents
Culture Documents
Introduction
A Python program is read by a parser. Python was designed to be a highly
readable language. The syntax of the Python programming language is the set of
rules which defines how a Python program will be written.
A Python program is divided into a number of logical lines and every logical line
is terminated by the token NEWLINE. A logical line is created from one or more
physical lines.
A line contains only spaces, tabs, formfeeds possibly a comment, is known as a
blank line, and Python interpreter ignores it.
A physical line is a sequence of characters terminated by an end-of-line
sequence (in windows it is called CR LF or return followed by a linefeed and in
Unix, it is called LF or linefeed). See the following example.
Comments in Python:
A comment begins with a hash character(#) which is not a part of the string literal
and ends at the end of the physical line. All characters after the # character up to
the end of the line are part of the comment and the Python interpreter ignores
them. See the following example. It should be noted that Python has no multi-
lines or block comments facility.
When you want to write a long code in a single line you can break the logical line
in two or more physical lines using backslash character(\). Therefore when a
physical line ends with a backslash characters(\) and not a part of a string literal
or comment then it can join another physical line. See the following example.
Indentation:
Python uses whitespace (spaces and tabs) to define program blocks whereas
other languages like C, C++ use braces ({}) to indicate blocks of codes for class,
functions or flow control. The number of whitespaces (spaces and tabs) in the
indentation is not fixed, but all statements within the block must be the indented
same amount. In the following program, the block statements have no
indentation.
Maximum line length : 79 characters which help users with a small display.
Use blank lines to separate top-level function and class definitions and single blank line to
separate methods definitions inside a class and larger blocks of code inside functions.
The following identifiers are used as reserved words of the language, and cannot
be used as ordinary identifiers.
as el if or
print() function
The print statement has been replaced with a print() function, with keyword
arguments to replace most of the special syntax of the old print statement.
print("Good Morning")
In Python, single, double and triple quotes are used to denote a string. Most use
single quotes when declaring a single character. Double quotes when declaring a
line and triple quotes when declaring a paragraph/multiple lines.
Commands
print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout,
flush=False)
Pretty Print
from pprint import pprint
pprint(<collection>, width=80, depth=None)
Example:
print("Python is very simple language")
Copy
Output:
Python is very simple language
Single Quotes Use:
Example:
print('Hello')
Copy
Output:
Hello
Triple Quotes Use:
Example:
print("""Python is very popular language.
Copy
Output:
Python is very Popular Language.
It is also friendly language.
Variable Use:
Strings can be assigned to variable say string1 and string2 which can called
when using the print statement.
Example:
str1 = 'Wel'
print(str1,'come')
Copy
Output:
Wel come
Example:
str1 = 'Welcome'
str2 = 'Python'
print(str1, str2)
Copy
Output:
Welcome Python
String Concatenation:
Example:
str1 = 'Python'
str2 = ':'
Copy
Output:
WelcomePython:
Using as String:
Example:
str1 = 'Python'
Copy
Output:
Welcome Python
Using other data types:
%d -> Integer
%e -> exponential
%f -> Float
%o -> Octal
%x -> Hexadecimal
This can be used for conversions inside the print statement itself.
Using as Integer:
Example:
print("Actual Number = %d" %15)
Copy
Output:
Actual Number = 15
Using as Exponential:
Example:
print("Exponential equivalent of the number = %e" %15)
Copy
Output:
Exponential equivalent of the number = 1.500000e+01
Using as Float:
Example:
print("Float of the number = %f" %15)
Copy
Output:
Float of the number = 15.000000
Using as Octal:
Example:
print("Octal equivalent of the number = %o" %15)
Copy
Output:
Octal equivalent of the number = 17
Using as Hexadecimal:
Example:
print("Hexadecimal equivalent of the number = %x" %15)
Copy
Output:
Hexadecimal equivalent of the number = f
Using multiple variables:
Example:
str1 = 'World'
str2 = ':'
Copy
Output:
Python World :
Other Examples of Print Statement:
The following are other different ways the print statement can be put to use.
Example-1:
Copy
Output:
Welcome to %Python language
Example-2:
Copy
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Example-3:
Copy
Output:
-w3r-w3r-w3r-w3r-w3r
Example-4:
Language:
\t1 Python
""")
Copy
Output:
Language:
1 Python
2 Java
3 JavaScript
Precision Width and Field Width:
Field width is the width of the entire number and precision is the width towards
the right. One can alter these widths based on the requirements.
Example-1:
Notice upto 6 decimal points are returned. To specify the number of decimal
points, '%(fieldwidth).(precisionwidth)f' is used.
print("%f" % 5.1234567890)
Copy
Output:
5.123457
Example-2:
Copy
Output:
5.12346
Example-3:
If the field width is set more than the necessary than the data right aligns itself to
adjust to the specified values.
print("%9.5f" % 5.1234567890)
Copy
Output:
5.12346
Example-4:
Copy
Output:
000000005.12346
Example-5:
For proper alignment, a space can be left blank in the field width so that when a
negative number is used, proper alignment is maintained.
print("% 9f" % 5.1234567890)
Copy
Output:
5.123457
-5.123457
Example-6:
'+' sign can be returned at the beginning of a positive number by adding a + sign
at the beginning of the field width.
print("%+9f" % 5.1234567890)
Copy
Output:
+5.123457
-5.123457
Example-7:
As mentioned above, the data right aligns itself when the field width mentioned is
larger than the actually field width. But left alignment can be done by specifying a
negative symbol in the field width.
print("%-9.4f" % 5.1234567890)
Copy
Output:
5.1235
Python Variable
Last update on February 28 2020 12:09:27 (UTC/GMT +8 hours)
No declaration required
The type (string, int, float etc.) of the variable is determined by Python
The interpreter allocates memory on the basis of the data type of a variable.
Case Sensitive
Choose meaningful name instead of short name. roll_no is better than rn.
Syntax:
<variable> = <expr>
Where the equal sign (=) is used to assign value (right side) to a variable name
(left side). See the following statements :
>>> Item_name = "Computer" #A String
>>> print(Item_name)
Computer
>>> print(Item_qty)
10
>>> print(Item_value)
1000.23
>>>
Copy
One thing is important, assignment statement read right to left only.
Example:
>>> 12 = a
>>>
Copy
Multiple Assignment
The basic assignment statement works for a single variable and a single
expression. You can also assign a single value to more than one variables
simultaneously.
Syntax:
var1=var2=var3...varn= = <expr>
Example:
x = y = z = 1
Now check the individual value in Python Shell.
>>> x = y = z = 1
>>> print(x)
>>> print(y)
>>> print(z)
1
>>>
Copy
Here is an another assignment statement where the variables assign many
values at the same time.
Syntax:
<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>
Example:
x, y, z = 1, 2, "abcd"
In the above example x, y and z simultaneously get the new values 1, 2 and
"abcd".
>>> x,y,z = 1,2,"abcd"
>>> print(x)
>>> print(y)
>>> print(z)
abcd
Copy
You can reuse variable names by simply assigning a new value to them :
>>> x = 100
>>> print(x)
100
>>> x = "Python"
>>> print(x)
Python
>>>
Copy
Other ways to define value
>>> five_millions = 5_000_000
>>> five_millions
Copy
Output:
5000000
>>> small_int = .35
>>> small_int
Copy
Output:
0.35
>>> c_thousand = 10e3
>>> c_thousand
Copy
Output:
10000.0
Swap variables
Python swap values in a single line and this applies to all objects in python.
Syntax:
var1, var2 = var2, var1
Example:
>>> x = 10
>>> y = 20
>>> print(x)
10
>>> print(y)
20
>>> x, y = y, x
>>> print(x)
20
>>> print(y)
10
>>>
Copy
Example:
var1 = "Python"
def func1():
var1 = "PHP"
def func2():
func1()
func2()
Copy
Output:
In side func1() var1 = PHP
In side func2() var1 = Python
You can use a global variable in other functions by declaring it as global keyword
:
Example:
def func1():
global var1
var1 = "PHP"
def func2():
func1()
func2()
Copy
Output:
In side func1() var1 = PHP
In side func2() var1 = PHP
Introduction
Type represents the kind of value and determines how the value can be used. All
data values in Python are encapsulated in relevant object classes. Everything in
Python is an object and every object has an identity, a type, and a value. Like
another object-oriented language such as Java or C++, there are several data
types which are built into Python. Extension modules which are written in C,
Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The
value of some objects can be changed. Objects whose value can be changed are
called mutable and objects whose value is unchangeable (once they are created)
are called immutable. Here are the details of Python data types
Numbers
Numbers are created by numeric literals. Numeric objects are immutable, which
means when an object is created its value cannot be changed.
Python has three distinct numeric types: integers, floating point numbers, and
complex numbers. Integers represent negative and positive integers without
fractional parts whereas floating point numbers represents negative and positive
numbers with fractional parts. In addition, Booleans are a subtype of plain
integers. See the following statements in Python shell.
Floats and Integers
>>> x = 8
>>> y = 7
>>> x+y
>>> x-y
>>> x/y
>>> x*y
Copy
Output:
15
1
1.1428571428571428
56
Exponent
>>> 4**3
>>> 3**4
Copy
Output:
64
81
inter division
>>> 12/3
>>> 64//4
>>> 15//3
Copy
Output:
4.0
16
5
Remainder
>>> 15 % 4
Copy
Output:
3
Mathematically, a complex number (generally used in engineering) is a number
of the form A+Bi where i is the imaginary number. Complex numbers have a real
and imaginary part. Python supports complex numbers either by specifying the
number in (real + imagJ) or (real + imagj) form or using a built-in method
complex(x, y). See the following statements in Python Shell.
Self-assignment
>>> count = 0
>>> count
Copy
Output:
2
>>> count -=2
>>> count
Copy
Output:
0
>>> count +=2
Copy
Output:
8
>>> count **=4
>>> count
Copy
Output:
4096
>>> count /=4
>>> count
Copy
Output:
1024.0
>>> count//=4
>>> count
Copy
Output:
256.0
>>> 15.0 //2
Copy
Output:
7.0
Order of operations
>>> (3+12) / 3
>>> 15 / (3 + 2)
Copy
Output:
5.0
3.0
Boolean (bool)
The simplest build-in type in Python is the bool type, it represents the truth values
False and True. See the following statements in Python shell.
Strings
In Python, a string type object is a sequence (left-to- right order) of characters.
Strings start and end with single or double quotes Python strings are immutable.
Single and double quoted strings are same and you can use a single quote within
a string when it is surrounded by double quote and vice versa. Declaring a string
is simple, see the following statements.
Special characters in strings
The backslash (\) character is used to introduce a special character. See the
following table.
\n Newline
\t Horizontal Tab
\\ Backslash
\' Single Quote
Character P Y T H O N T U T
See the following statements to access single character from various positions.
Conversion
>>> float("4.5")
>>> int("25")
>>> int(5.625)
>>> float(6)
>>> int(True)
>>> float(False)
>>> str(True)
>>> bool(0)
>>> bool(223.5)
Copy
Output:
4.5
25
5
6.0
1
0.0
'True'
False
True
True
Tuples
A tuple is a container which holds a series of comma-separated values (items or
elements) between parentheses. Tuples are immutable (i.e. you cannot change
its content once created) and can hold mix data types.
Creating Tuples
To create an empty tuple or create a tuple with single element use the following
commands.
Elements of a tuple are indexed like other sequences. The tuple indices start at
0. See the following statements.
Tuples are immutable which means it's items values are unchangeable. See the
following statements.
Slicing a tuple
Like other sequences like strings, tuples can be sliced. Slicing a tuple creates a
new tuple but it does not change the original tuple.
Lists
A list is a container which holds comma-separated values (items or elements)
between square brackets where Items or elements need not all have the same
type.
Creating Lists
A list without any element is called an empty list. See the following statements.
List indices
List indices work the same way as string indices, list indices start at 0. If an index
has a positive value it counts from the beginning and similarly it counts backward
if the index has a negative value. As positive integers are used to index from the
left end and negative integers are used to index from the right end, so every item
of a list gives two alternatives indices. Let create a list called color_list with four
items.
color_list=["RED", "Blue", "Green", "Black"]
If you give any index value which is out of range then interpreter creates an error
message. See the following statements.
List Slices
Lists can be sliced like strings and other sequences. The syntax of list slices is
easy :
sliced_list = List_Name[startIndex:endIndex]
This refers to the items of a list starting at index startIndex and stopping just
before index endIndex. The default values for list are 0 (startIndex) and the end
(endIndex) of the list. If you omit both indices, the slice makes a copy of the
original list. See the following statements.
Sets
A set is an unordered collection of unique elements. Basic uses include dealing
with set theory (which support mathematical operations like union, intersection,
difference, and symmetric difference) or eliminating duplicate entries. See the
following statements.
Dictionaries
Python dictionary is a container of the unordered set of objects like lists.The
objects are surrounded by curly braces { }. The items in a dictionary are a
comma-separated list of key:value pairs where keys and values are Python data
type. Each object or value accessed by key and keys are unique in the
dictionary. As keys are used for indexing, they must be the immutable type
(string, number, or tuple). You can create an empty dictionary using empty curly
braces
None
This type has a single value. There is a single object with this value. This object
is accessed through the built-in name None. It is used to signify the absence of a
value in many situations, e.g., it is returned from functions that don't explicitly
return anything. Its truth value is false.
Python Operators
Last update on June 06 2020 10:33:31 (UTC/GMT +8 hours)
Contents:
Operators commands
Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators
Bitwise Operator
Conditional Operators
Operator precedence
Operator: Commands
// Floor Division x/ y The division of operands where the result is the quotient in which th
Python Comparison Operators
< Less than x<y True if x (left-hand argument) is less than y (righ
>= Greater than or equal to x>=y True if x (left-hand argument) is greater than or e
<= Less than or equal to x<=y True if x (left-hand argument) is less than or equa
not (x not y) If a condition is true then Logical not operator will make false.
+= x+=y x = x + y Adds 2 numbers and assigns the result to left operand.
*= x*= y x = x*y Multiplies 2 numbers and assigns the result to left operand.
/= x/= y x = x/y Divides 2 numbers and assigns the result to left operand.
%= x%= y x = x%y Computes the modulus of 2 numbers and assigns the result to left
**= x**=y x = x**y Performs exponential (power) calculation on operators and assign
//= x//=y x = x//y Performs floor division on operators and assign value to the left o
<< Shift left x <<y Shift the bits of x, y steps to the left
>> Shift right x >>y Shift the bits of x, y steps to the right.
Conditional Operators
Conditional expressions or ternary operator have the lowest priority of all Python
operations. The expression x if C else y first evaluates the condition, C (not x); if
C is true, x is evaluated and its value is returned; otherwise, y is evaluated and
its value is returned.
Operator precedence
Operator precedence determines how operators are parsed concerning each
other. The following table summarizes the operator precedence in Python, from
lowest precedence (least binding) to highest precedence (most binding).
Operators in the same box have the same precedence. Unless the syntax is
explicitly given, operators are binary. Operators in the same box group left to
right (except for exponentiation, which groups from right to left).
Note: Comparisons, membership tests, and identity tests, all have the same
precedence and have a left-to-right chaining feature as described in the
Comparisons section.
:= Assignment expression
or Boolean OR
in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership te
| Bitwise OR
^ Bitwise XOR
** Exponentiation
if..elif..else
The if-elif-else statement is used to conditionally execute a statement or a block
of statements. Conditions can be true or false, execute one thing when the
condition is true, something else when the condition is false.
Contents:
if statement
if .. else statement
Nested if .. else
Define a negative if
if statement
The Python if statement is same as it is with other programming languages. It
executes a set of statements conditionally, based on the value of a logical
expression.
Syntax:
if expression :
statement_1
statement_2
....
In the above case, expression specifies the conditions which are based on
Boolean expression. When a Boolean expression is evaluated it produces either
a value of true or false. If the expression evaluates true the same amount of
indented statement(s) following if will be executed. This group of the statement(s)
is called a block.
if .. else statement
In Python if .. else statement, if has two blocks, one following the expression and
other following the else clause. Here is the syntax.
Syntax:
if expression :
statement_1
statement_2
....
else :
statement_3
statement_4
....
In the above case if the expression evaluates to true the same amount of
indented statements(s) following if will be executed and if the expression
evaluates to false the same amount of indented statements(s) following else will
be executed. See the following example. The program will print the second print
statement as the value of a is 10.
a=10
if(a>10):
else :
print("Value of a is 10")
Copy
Output:
Value of a is 10
Flowchart:
if expression1 :
statement_1
statement_2
....
elif expression2 :
statement_3
statement_4
....
elif expression3 :
statement_5
statement_6
....................
else :
statement_7
statement_8
In the above case Python evaluates each expression (i.e. the condition) one by
one and if a true condition is found the statement(s) block under that expression
will be executed. If no true condition is found the statement(s) block under else
will be executed. In the following example, we have applied if, series of elif and
else to get the type of a variable.
var1 = 1+2j
if (type(var1) == int):
else:
Copy
Output:
Type of the variable is Complex
Flowchart:
Syntax:
if expression1 :
if expression2 :
statement_3
statement_4
....
else :
statement_5
statement_6
....
else :
statement_7
statement_8
In the above syntax expression1 is checked first, if it evaluates to true then the
program control goes to next if - else part otherwise it goes to the last else
statement and executes statement_7, statement_8 etc.. Within the if - else if
expression2 evaluates true then statement_3, statement_4 will execute
otherwise statement_5, statement_6 will execute. See the following example.
age = 38
else:
print("Tic kit price is $20")
else:
Copy
Output :
You are eligible to see the Football match.
Tic kit price is $20
In the above example age is set to 38, therefore the first expression (age >= 11)
evaluates to True and the associated print statement prints the string "You are
eligible to see the Football match". There after program control goes to next if
statement and the condition ( 38 is outside <=20 or >=60) is matched and prints
"Tic kit price is $12".
Flowchart:
x = False
y = True
#The validation will be True only if all the expressions generate a value True
if x and y:
else:
Copy
Output:
x is False or y is False or both x and y are False
s = 'jQuery'
#create a list
if s in l:
Copy
Output:
jQuery Tutorial
jQuery Tutorial
Write an if-else in a single line of code
#create a integer
n = 150
print(n)
print(result)
Copy
Output:
150
21.428571428571427
Define a negative if
If a condition is true the not operator is used to reverse the logical state, then
logical not operator will make it false.
#create a integer
x = 20
print(x)
#uses the not operator to reverse the result of the logical expression
if not x == 50:
else:
for loop
Like most other languages, Python has for loops, but it differs a bit from other like
C or Pascal. In Python for loop is used to iterate over the items of any sequence
including the Python list, string, tuple etc. The for loop is also used to access
elements from a container (for example list, string, tuple) using built-in function
range().
Syntax:
for variable_name in sequence :
statement_1
statement_2
....
Parameter:
Name Description
variable_name It indicates target variable which will set a new value for each iteration of the loop.
sequence A sequence of values that will be assigned to the target variable variable_name. Values a
built-in function range().
print(c)
Red
Blue
Green
Black
>>>
Copy
Syntax:
for <variable> in range(<number>):
Example:
>>> for a in range(4):
print(a)
>>>
Copy
Syntax:
for "variable" in range("start_number", "end_number"):
Example:
>>> for a in range(2,7):
print(a)
>>>
Copy
Example:
>>> for a in range(2,19,5):
print(a)
12
17
>>>
Copy
The following example counts the number of even and odd numbers from a
series of numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
if x % 2:
count_odd+=1
else:
count_even+=1
Copy
Output:
Number of even numbers:4
Number of odd numbers: 5
In the above example a tuple named numbers is declared which holds the
integers 1 to 9.
The best way to check if a given number is even or odd is to use the modulus
operator (%).
The operator returns the remainder when dividing two numbers.
Modulus of 8 % 2 returns 0 as 8 is divided by 2, therefore 8 is even and modulus
of 5 % 2 returns 1 therefore 5 is odd.
The for loop iterates through the tuple and we test modulus of x % 2 is true or
not, for every item in the tuple and the process will continue until we rich the end
of the tuple.
When it is true count_even increase by one otherwise count_odd is increased by
one.
Finally, we print the number of even and odd numbers through print statements.
In the following example for loop iterates through the list "datalist" and prints
each item and its corresponding Python type.
datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],
{"class":'V', "section":'A'}]
Copy
Output:
Type of 1452 is <class 'int'>
Type of 11.23 is <class 'float'>
Type of (1+2j) is <class 'complex'>
Type of True is <class 'bool'>
Type of w3resource is <class 'str'>
Type of (0, -1) is <class 'tuple'>
Type of [5, 12] is <class 'list'>
Type of {'section': 'A', 'class': 'V'} is <class 'dict'>
Example: Iterating over dictionary
In the following example for loop iterates through the dictionary "color" through its
keys and prints each key.
>>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
print(key)
c2
c1
c3
>>>
Copy
print(value)
Green
Red
Orange
>>>
Copy
You can attach an optional else clause with for statement, in this case, syntax will
be -
for variable_name in sequence :
statement_1
statement_2
....
else :
statement_3
statement_4
....
The else clause is only executed after completing the for loop. If a break
statement executes in first program block and terminates the loop then the else
clause does not execute
While loop
Loops are used to repeatedly execute a block of program statements. The basic
loop structure in Python is while loop. Here is the syntax.
Syntax:
while (expression) :
statement_1
statement_2
....
The while loop runs as long as the expression (condition) evaluates to True and
execute the program block. The condition is checked every time at the beginning
of the loop and the first time when the expression evaluates to False, the loop
stops without executing any remaining statement(s). The following example
prints the digits 0 to 4 as we set the condition x < 5.
x = 0;
print(x)
x += 1
Copy
Output:
0
1
2
3
4
One thing we should remember that a while loop tests its condition before the
body of the loop (block of program statements) is executed. If the initial test
returns false, the body is not executed at all. For example the following code
never prints out anything since before executing the condition evaluates to false.
x = 10;
print(x)
x += 1
Copy
Flowchart:
The following while loop is an infinite loop, using True as the condition:
x = 10;
while (True):
print(x)
x += 1
Copy
Flowchart:
You can attach an optional else clause with while statement, in this case, syntax
will be -
while (expression) :
statement_1
statement_2
......
else :
statement_3
statement_4
......
The while loop repeatedly tests the expression (condition) and, if it is true,
executes the first block of program statements. The else clause is only executed
when the condition is false it may be the first time it is tested and will not execute
if the loop breaks, or if an exception is raised. If a break statement executes in
first program block and terminates the loop then the else clause does not
execute. In the following example, while loop calculates the sum of the integers
from 0 to 9 and after completing the loop, else statement executes.
x = 0;
s = 0
s = s + x
x = x + 1
else :
Copy
Output:
The sum of first 9 integers: 45
Flowchart:
Example: while loop with if-else and break statement
x = 1;
s = 0
s = s + x
x = x + 1
if (x == 5):
break
else :
Copy
Output:
The sum of 5 numbers is : 10
In the above example the loop is terminated when x becomes 5. Here we use
break statement to terminate the while loop without completing it, therefore
program control goes to outside the while - else structure and execute the next
print statement.
Flowchart:
Python break, continue statement
Last update on February 28 2020 12:05:29 (UTC/GMT +8 hours)
break statement
The break statement is used to exit a for or a while loop. The purpose of this
statement is to end the execution of the loop (for or while) immediately and the
program control goes to the statement after the last statement of the loop. If there
is an optional else statement in while or for loop it skips the optional clause also.
Here is the syntax.
Syntax:
while (expression1) :
statement_1
statement_2
......
if expression2 :
break
for variable_name in sequence :
statement_1
statement_2
if expression3 :
break
Example: break in for loop
In the following example for loop breaks when the count value is 5. The print
statement after the for loop displays the sum of first 5 elements of the tuple
numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
num_sum = 0
count = 0
for x in numbers:
num_sum = num_sum + x
count = count + 1
if count == 5:
break
Copy
Output:
Sum of first 5 integers is: 15
Example: break in while loop
In the following example while loop breaks when the count value is 5. The print
statement after the while loop displays the value of num_sum (i.e. 0+1+2+3+4).
num_sum = 0
count = 0
while(count<10):
count = count + 1
if count== 5:
break
Copy
Output:
Sum of first 5 integers is : 10
continue statement
The continue statement is used in a while or for loop to take the control to the top
of the loop without executing the rest statements inside the loop. Here is a simple
example.
for x in range(7):
if (x == 3 or x==6):
continue
print(x)
Copy
Output:
0
1
2
4
5
In the above example, the for loop prints all the numbers from 0 to 6 except 3
and 6 as the continue statement returns the control of the loop to the top
Bytes, Bytearray
Python supports a range of types to store sequences. There are six sequence
types: strings, byte sequences (bytes objects), byte arrays (bytearray objects),
lists, tuples, and range objects.
Strings contain Unicode characters. Their literals are written in single or double
quotes : 'python', "data". Bytes and bytearray objects contain single bytes – the
former is immutable while the latter is a mutable sequence. Bytes objects can be
constructed the constructor, bytes(), and from literals; use a b prefix with normal
string syntax: b'python'. To construct byte arrays, use the bytearray() function.
Contents
Bytes literals
Define a mapping table characters for use with a bytes object in Python
Bytes literals
bytesliteral ::= bytesprefix(shortbytes | longbytes)
bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR"
shortbytes ::= "'" shortbytesitem* "'" | '"' shortbytesitem*
'"'
longbytes ::= "'''" longbytesitem* "'''" | '"""'
longbytesitem* '"""'
shortbytesitem ::= shortbyteschar | bytesescapeseq
longbytesitem ::= longbyteschar | bytesescapeseq
shortbyteschar ::= <any ASCII character except "\" or newline or
the quote>
longbyteschar ::= <any ASCII character except "\">
bytesescapeseq ::= "\" <any ASCII character>
Syntax:
bytearray([source[, encoding[, errors]]])
The optional source parameter can be used to initialize the array in a few
different ways:
If it is a string, you must also give the encoding (and optionally, errors) parameters;
bytearray() then converts the string to bytes using str.encode().
If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be
used to initialize the bytes array.
If it is iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as
the initial contents of the array.
Code :
>>> x = b"Bytes objects are immutable sequences of single bytes"
>>> print(x)
>>>
Copy
Example-2:
Code:
#triple single or double quotes allows multiple lines
x = b'''Python Tutorial,
Javascript Tutorial,
MySQL Tutorial'''
print(x)
Copy
Output:
b'Python Tutorial,\nJavascript Tutorial,\nMySQL Tutorial'
Example-3 :
Code :
#created from a iterable of ints, string, bytes or buffer objects.
print(x)
Copy
Output:
b'Python, bytes'
Code:
#create a bytes object
print(x)
Copy
Output:
b'El ni\xc3\xb1o come camar\xc3\xb3n'
Example-2:
Code:
# create a string using the decode() method of bytes.
#This method takes an encoding argument, such as UTF-8, and optionally an errors
argument.
s = x.decode()
print(type(s))
print(s)
Copy
Output:
Code:
#create a bytes object encoded using 'cp855'
x = b'\xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1'
print(x)
y = x.decode('cp855')
print(y)
Copy
Output:
b'\xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1'
привет мир
Convert hex string to bytes
Example-1:
Code :
#create a string with hexadecimal data
x = '45678c6c56f205876f72c64'
print(x)
Copy
Output:
45678c6c56f205876f72c64
Example-2:
Code :
#this class method returns a bytes object, decoding the given string object.
x = '45678c6c56f205876f72c64'
y = bytes.fromhex(x)
Copy
Output:
b'.\xf0\xf1\xf2'
Python
Example-1:
Code:
#return an integer representing the Unicode code point of that character.
x = ord(b'm')
print(x)
Copy
Output:
109
Example-2:
Code:
#create a bytes object
y = b'Python bytes'
z = list(y)
print(z)
Copy
Output:
[80, 121, 116, 104, 111, 110, 32, 98, 121, 116, 101, 115]
object in Python
Example-1:
Code:
#create a str
print(x)
Copy
Output:
b'Python mapping table characters'
Example-2:
Code:
b_table = bytes.maketrans(b'abcdef', b'uvwxyz')
print(type(b_table))
print(b_table)
Copy
Output:
<class 'bytes'>
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\
x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%
&\'()*+,-./0123456789:;<=>?
@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`uvwxyzghijklmnopqrstuvwxyz{|}~\
x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x
8f\x
90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa
0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0
\xb1\
xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\x
c2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd
2\xd3
\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\
xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\x
f4\xf
5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
Example-3:
Code:
b_table = bytes.maketrans(b'abcdef', b'uvwxyz')
str = 'Write a Python function to find a distinct pair of numbers whose product is
odd from a sequence of integer values.'
b_new = str.translate(b_table)
print(b_new)
Copy
Output:
Writy u Python zunwtion to zinx u xistinwt puir oz numvyrs whosy
proxuwt is oxx zrom u syquynwy oz intygyr vuluys.
>>> binascii.hexlify("Python".encode("utf8"))
b'507974686f6e'
>>> binascii.unhexlify(_).decode("utf8")
'Python'
>>>
Copy
objects in Python
>>> #this method return a single character based on the integer value.
>>> x = chr(60)
>>> print(x)
<
>>> x = chr(50)
>>> print(x)
>>> y = [70, 111, 106, 94, 101, 100, 22, 95, 105, 22, 91, 87, 125, 135]
>>> print(y)
[70, 111, 106, 94, 101, 100, 22, 95, 105, 22, 91, 87, 125, 135]
>>> #create a bytes object from a list of integers in the range 0 through 255.
>>> z = bytes(y)
>>> print(z)
b'Foj^ed\x16_i\x16[W}\x87'
>>>
Copy
>>> print(x)
Python, Bytes
>>> #know the length of the string using the len() function
>>> print(len(x))
13
>>> print(y)
b'Python, Bytes'
>>> #know the length of the bytes object using the len() function
>>> print(len(y))
13
>>>
Copy
>>> print(x)
b'byte 213'
>>> print(x * 5)
>>> x1 = bytes([70, 111, 106, 94, 101, 100, 22, 95, 105, 22, 91, 87, 125, 135])
>>> x2 = b"Python"
>>> #The + operator allow create a new bytes object joining two or more bytes.
>>> x = x1 + x2
>>> print(x)
b'Foj^ed\x16_i\x16[W}\x87Python'
>>> print(x)
b'PythonBytesBytesBytes$'
>>>
Copy
>>> print(y)
[80, 121, 116, 104, 111, 110, 32, 105, 115, 32, 101, 97, 115, 121]
>>> x1 = bytes([70, 111, 106, 94, 101, 100, 22, 95, 105, 22, 91, 87, 125, 135])
>>> print(x1)
b'Foj^ed\x16_i\x16[W}\x87'
>>> #is similar to the handling of lists, the index is defined in brackets
>>> x = y[3]
>>> print(x)
104
>>> print(chr(x))
>>> #can also use negative indices to get a byte from bytes object
>>> x = [-8]
>>> print(x)
[-8]
>>> x = y[-8]
>>> print(x)
110
>>> print(chr(x))
>>>
Copy
>>> print(x)
bytearray(b'Python Bytes')
bytearray(b'Python Bytes')
>>> #create a bytearray from a list of integers in the range 0 through 255
>>> x = bytearray([94, 91, 101, 125, 111, 35, 120, 101, 115, 101, 200])
>>> print(x)
bytearray(b'^[e}o#xese\xc8')
>>>
Copy
>>> print(x)
bytearray(b'Python bytearray')
>>> print(x)
bytearray(b'Python bytey')
>>> print(x)
>>> #can use the methods of mutable type iterable objects as the lists
>>> x.append(45)
>>> print(x)
>>>
Copy
>>> x = bytes([105, 100, 107, 112, 132, 118, 107, 112, 200])
>>> print(x)
b'idkp\x84vkp\xc8'
>>> x1 = bytearray(x)
>>> print(x1)
bytearray(b'idkp\x84vkp\xc8')
>>>
Copy
>>> print(x)
b'Python slice'
>>> #b[start:stop] the start index is inclusive and the end index is exclusive.
>>> x1 = x[2:6]
>>> print(x1)
b'thon'
>>> #if the start index isn't defined, is starts from the beginning
>>> x1 = x[-5:]
>>> print(x1)
b'slice'
>>> #if the end index isn't defined, it goes until the end
>>> x1 = x[:4]
>>> print(x1)
b'Pyth'
>>> x1 = x[:]
>>> print(x1)
b'Python slice'
>>>
Copy
>>> print(x)
Python String
>>> print(y)
b'Python String'
>>> x = "Python"
>>> print(x)
Python
>>> print(y)
Python Regular Expression
Last update on February 28 2020 12:15:20 (UTC/GMT +8 hours)
Regular Expression
A regular expression (or RE) specifies a set of strings that matches it; the
functions in this module let you check if a particular string matches a given
regular expression (or if a given regular expression matches a particular string,
which comes down to the same thing).
Contents:
Group Comparison
Back Reference
Substitute String
Look around
Match email
Match URL
Match IP address
Lexer
Special Description
characters
. (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag
including a newline.
^ (Caret.) Matches the beginning of the string or line. For example /^A/ does not match the 'A'
"Articles of life"
$ Matches the end of the string or line. For example, /e$/ does not match the 't' in "exact", but d
* Matches the previous character 0 or more times. For example, /bo*/ matches 'boo' in "A boot
nothing in "A going concern".
+ Matches the previous character 1 or more times. For example, /a+/ matches the 'a' in "Daniel
? Matches the previous character 0 or 1 time. For example, /r?eu?/ matches the 're' in "w3resou
*?, +?, ?? The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes t
matched against '<a> b <c>', it will match the entire string, and not just '<a>'. Adding ? after
non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE
{m} Specifies that exactly m copies of the previous RE should be matched; fewer matches cause t
example, b{5} will match exactly five 'b' characters, but not four.
{m,n} Causes the resulting RE to match from m to n repetitions of the preceding RE. For example,
Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound
thousand 'a' characters followed by a 'b', but not 'aaab'.
{m,n}? Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to
non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa',
while a{3,5}? will only match 3 characters.
\ Either escapes special characters (permitting you to match characters like '*', '?', and s
special sequences are discussed below.
Characters can be listed individually, e.g. [amk] will match 'a', 'm', or 'k'.
Ranges of characters can be indicated by giving two characters and separating them by a '-', for ex
[0-5][0-9] will match all the two-digits numbers from 00 to 59, and [0-9A-Fa-f] will match any he
placed as the first or last character (e.g. [-a] or [a-]), it will match a literal '-'.
Special characters lose their special meaning inside sets. For example, [(+*)] will match any of th
Character classes such as \w or \S (defined below) are also accepted inside a set, although the cha
LOCALE mode is in force.
Characters that are not within a range can be matched by complementing the set. If the first chara
the set will be matched. For example, [^5] will match any character except '5', and [^^] will match
it’s not the first character in the set.
To match a literal ']' inside a set, precede it with a backslash, or place it at the beginning of the set
match a parenthesis.
| A|B, where A and B can be arbitrary REs, creates a regular expression that will match either
separated by the '|' in this way. This can be used inside groups (see below) as well.
(...) Matches whatever regular expression is inside the parentheses, and indicates the start and end
retrieved after a match has been performed, and can be matched later in the string with the \n
match the literals '(' or ')', use \( or \), or enclose them inside a character class: [(], [)].
(?...) This is an extension notation (a '?' following a '(' is not meaningful otherwise). The first chara
and further syntax of the construct is. Extensions usually do not create a new group; (?P<nam
Following are the currently supported extensions.
(?aiLmsux) (One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty strin
(ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (do
re.X (verbose), for the entire regular expression.
(?:...) A non-capturing version of regular parentheses. Matches whatever regular expression is insid
by the group cannot be retrieved after performing a match or referenced later in the pattern.
(?imsx-imsx:...) (Zero or more letters from the set 'i', 'm', 's', 'x', optionally followed by '-' followed by one or
or removes the corresponding flags: re.I (ignore case), re.M (multi-line), re.S (dot matches al
expression.
(?P<name>...) Similar to regular parentheses, but the substring matched by the group is accessible vi
names must be valid Python identifiers, and each group name must be defined only on
group is also a numbered group, just as if the group were not named.
(?P=name) A backreference to a named group; it matches whatever text was matched by the earlier grou
(?=...) Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead
match 'Isaac ' only if it’s followed by 'Asimov'.
(?!...) Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac
followed by 'Asimov'.
(?<=...) Matches if the current position in the string is preceded by a match for ... that ends at
positive lookbehind assertion. (?<=abc)def will find a match in 'abcdef', since the look
check if the contained pattern matches.
>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'
This example looks for a word following a hyphen:
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
(?<!...) Matches if the current position in the string is not preceded by a match for .... This is called a
positive lookbehind assertions, the contained pattern must only match strings of some fixed l
lookbehind assertions may match at the beginning of the string being searched.
(?(id/name)yes- Will try to match with yes-pattern if the group with given id or name exists, and with no-patt
pattern|no- be omitted. For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$) is a poor email matching pattern
pattern) well as 'user@host.com', but not with '<user@host.com' nor 'user@host.com>'. The special s
list below. If the ordinary character is not an ASCII digit or an ASCII letter, then the resultin
example, \$ matches the character '$'.
\number Matches the contents of the group of the same number. Groups are numbered starting from 1
55', but not 'thethe' (note the space after the group). This special sequence can only be used to
digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group mat
number. Inside the '[' and ']' of a character class, all numeric escapes are treated as characters
\b Matches the empty string, but only at the beginning or end of a word. A word is defin
\B Matches the empty string, but only when it is not at the beginning or end of a word. This mea
but not 'py', 'py.', or 'py!'. \B is just the opposite of \b, so word characters in Unicode patterns
although this can be changed by using the ASCII flag. Word boundaries are determined by th
\d Matches any character which is a digit. Equivalent to [0-9]. For example, /\d/ or /[0-9]
example."
\D Matches any character which is not a decimal digit. This is the opposite of \d. If the ASCII fl
9] (but the flag affects the entire regular expression, so in such cases using an explicit [^0-9]
\s Matches any white space character (including tab, new line, carriage return, form feed
For example, /\s\w*/ matches ' apple' in "An apple."
Matches characters considered whitespace in the ASCII character set; this is equivalen
\S Matches any character which is not a whitespace character. This is the opposite of \s. If the A
of [^ \t\n\r\f\v] (but the flag affects the entire regular expression, so in such cases using an ex
\w Matches characters considered alphanumeric in the ASCII character set; this is equiva
is used, matches characters considered alphanumeric in the current locale and the und
# open tag
>>> import re
True
>>> import re
True
>>> import re
>>> re.search('<[^/>][^>]*>', '<img src="/img">') != None
True
>>> import re
False
# close tag
>>> import re
True
# self close
>>> import re
True
Copy
re.findall() match string :
# split all string
>>> import re
>>> import re
>>> x = urllib.urlopen('https://www.w3resource.org')
open tags
close tags
['</script>', '</title>']
Copy
Group Comparison :
# (...) group a regular expression
>>> import re
>>> mon
>>> mon.groups()
>>> mon.group()
'2018-09-01')
>>> mon.group(1)
'2018'
>>> mon.group(2)
'09'
>>> mon.group(3)
'01'
# Nesting groups
>>> import re
>>> mon.groups()
>>> mon.group()
'2018-09-01'
>>> mon.group(1)
'2018-09-01'
>>> mon.group(2)
'2018-09'
>>> mon.group(3)
'2018'
Copy
Non capturing group :
# non capturing group
>>> import re
>>> mon.groups()
('w3resource.com', '/')
# capturing group
>>> import re
>>> mon.groups()
>>> import re
True
>>> import re
True
>>> import re
False
>>> import re
True
True
False
Copy
Named Grouping (?P<name>) :
# group reference ``(?P<name>...)``
>>> import re
'2018'
>>> mon.group('month')
'09'
>>> mon.group('day')
'01'
>>> import re
>>> re.search('^(?P<char>[a-z])(?P=char)','aa')
Copy
Substitute String :
# basic substitute
>>> import re
'4 5 6 '
>>> import re
>>> re.sub(r'(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1/',date)
'09/01/2018/'
# camelcase to underscore
...
>>> convert('SentenceCase')
'sentence_case'
>>> convert('SentenceSentenceCase')
'sentence_sentence_case'
>>> convert('SampleExampleHTTPServer')
'sample_example_http_server'
Copy
Look around :
# basic
>>> import re
' 5 6 789'
'567 8 9 '
'567 8 9 '
>>> re.sub('(?<!\d{3})', ' ', '56789')
' 5 6 789'
Copy
Match common username or password :
>>> import re
True
True
Copy
Match hex color value :
>>> import re
Copy
Match email :
>>> import re
>>> re.match('^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$',
'citi.world@example.com')
# or
>>> import re
[a-zA-Z0-9.-]+
\.[a-zA-Z]{2,4})*$''', re.X)
>>> example.match('citi.world@example.citi.com')
>>> example.match('citi%world@example.citi.com')
Copy
Match URL :
>>> import re
>>> example.match('www.yahoo.com')
>>> example.match('http://www.example')
>>> example.match('http://www.example/w3r.html')
>>> example.match('http://www.example/w3r!.html')
>>> example
re.compile('^(https?:\\/\\/)?\n([\\da-z\\.-]+)\n\\.([a-z\\.]
{2,6})\n([\\/\\w \\.-]*)\\/?$\n', re.VERBOSE)
Copy
Match IP address :
notation description
>>> import re
... |2[0-4][0-9]
... |[1]?[0-9][0-9]?)\.){3}
... (?:25[0-5]
... |2[0-4][0-9]
>>> example.match('192.168.1.1')
>>> example.match('255.255.255.0')
>>> example.match('172.17.0.5')
True
Copy
Match Mac address :
>>> import random
>>> mac
'05:38:64:60:55:63'
>>> import re
... [0-9a-f]{2}
True
Copy
Lexer :
>>> import re
r'(?P<PLUS>\+)',
r'(?P<MINUS>-)',
r'(?P<TIMES>\*)',
r'(?P<DIVIDE>/)',
r'(?P<WS>\s+)']
scan = lex.scanner(text)
print(_t)
Token(type='NUMBER', value='9')
Token(type='PLUS', value='+')
Token(type='NUMBER', value='5')
Token(type='TIMES', value='*')
Token(type='NUMBER', value='2')
Token(type='MINUS', value='-')
Token(type='NUMBER', value='7')
>>> tokens
Python String
Last update on February 28 2020 12:15:43 (UTC/GMT +8 hours)
String
Python has a built-in string class named "str" with many useful features. String
literals can be enclosed by either single or double, although single quotes are
more commonly used.
Backslash escapes work the usual way within both single and double quoted
literals -- e.g. \n \' \". A double quoted string literal can contain single quotes
without any fuss (e.g. "I wouldn't be a painter") and likewise single quoted string
can contain double quotes.
A string literal can span multiple lines, use triple quotes to start and end them.
You can use single quotes too, but there must be a backslash \ at the end of
each line to escape the newline.
Contents :
String commands
String length
String slices
String: Commands
# Strips all whitespace characters from both ends.
<str> = <str>.strip()
# Strips all passed characters from both ends.
<str> = <str>.strip('<chars>')
Char
# Converts int to unicode char.
<str> = chr(<int>)
# Converts unicode char to int.
<int> = ord(<str>)
>>> ord('0'), ord('9')
(48, 57)
>>> ord('A'), ord('Z')
(65, 90)
ord('a'), ord('z')
(97, 122)
Initialize string literals in Python:
>>> s = "Python string"
>>> print(s)
Python string
>>> print(s)
>>> print(s)
>>> print(s)
JavaScript tutorial
>>> print(s)
jQuery exercises
JavaScript tutorial
>>> s = 'jQuery exercises\n JavaScript tutorial\n Python tutorial and exercises ...'
>>> print(s)
jQuery exercises
JavaScript tutorial
>>>
Copy
Access character(s) from a string:
Characters in a string can be accessed using the standard [ ] syntax, and like
Java and C++, Python uses zero-based indexing, so if str is 'hello' str[2] is 'l'. If
the index is out of bounds for the string, Python raises an error.
>>> a = "Python string"
Python string
>>> b = a[2]
>>> print(b)
>>> a[0]
'P'
>>>
Copy
Explanation :
The above statement selects character at position number 2 from a and assigns it to b.
The expression in brackets is called an index that indicates which character we are
interested.
The index is an offset from the beginning of the string, and the offset of the first letter is zero.
>>> b = a[4+3]
>>> print(b)
>>>
Copy
The value of the index has to be an integer.
>>> a = "Python string"
>>> a[2.3]
>>>
Copy
Negative indices:
Alternatively, we can use negative indices, which count backward from the end of
the
>>> a[-2]
'n'
>>> a[-8]
'n'
>>>
Copy
Python strings are immutable:
Python strings are "immutable" which means they cannot be changed after they are created
>>> a = "PYTHON"
>>> print(b)
XYTHON
>>> print(a)
PYTHON
>>>
Copy
Python String concatenation:
>>> print(a)
PythonString
>>>
Copy
You can also use += to concatenate two strings.
>>> a = "Java"
>>> b = "Script"
>>> a+=b
>>> print(a)
JavaScript
>>>
Copy
Using '*' operator:
>>> a = "Python" + "String"
>>> print(b)
<PythonStringPythonStringPythonString>
>>>
Copy
String length:
>>> len(a)
13
>>> a[13]
>>> a[12]
'g'
>>>
Copy
Traverse string with a while or for loop
They start at the beginning, select each character, in turn, do something to it, and continue
until the end.
Code:
a = "STRING"
i = 0
c = a[i]
print(c)
i = i + 1
Copy
Output:
>>>
S
T
R
I
N
G
>>>
Traversal with a for loop :
Code:
a = "Python"
i = 0
new=" "
b=a[i]
new = new+b
i = i + 1
print(b)
print(new)
Copy
Output:
>>>
P
P
y
Py
t
Pyt
h
Pyth
o
Pytho
n
Python
>>>
String slices:
A segment of a string is called a slice. The "slice" syntax is used to get sub-parts
of a string. The slice s[start:end] is the elements beginning at the start (p) and
extending up to but not including end (q).
The operator [p:q] returns the part of the string from the pth character to the qth character,
including the first but excluding the last.
If we omit the first index (before the colon), the slice starts at the beginning of the string.
If you omit the second index, the slice goes to the end of the string:
If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks.
Example-1
>> s = "Python"
Copy
s[1:4] is 'yth' -- chars starting at index 1 and extending up to but not including index 4
s[1:] is 'ython' -- omitting either index defaults to the start or end of the string
s[1:100] is 'ython' -- an index that is too big is truncated down to the string length
Python uses negative numbers to give easy access to the chars at the end of the
string. Negative index numbers count back from the end of the string:
s[-3:] is 'hon' -- starting with the 3rd char from the end and extending to the end of the string.
Example-2
>>> a = "Python String"
Pytho
>>> print(a[6:11])
Stri
>>> print(a[5:13])
n String
>>>
Copy
>>> a = "Python String"
>>> print(a[:8])
Python S
>>> print(a[4:])
on String
>>> print(a[6:3])
>>>
Copy
Example-3
>>> a = "PYTHON"
>>> a[3]
'H'
>>> a[0:4]
'PYTH'
>>> a[3:5]
'HO'
...
>>> a[:2]
'PY'
...
>>> a[3:]
'HON'
>>>
Copy
Search a character in a string:
Code:
def search(char,str):
L=len(str)
print(L)
i = 0
while i < L:
if str[i]== char:
return 1
i = i + 1
return -1
print(search("P","PYTHON"))
Copy
Output:
>>>
6
1
>>>
It takes a character and finds the index where that character appears in a string.
Another example
def search(char,str):
L=len(str)
print(L)
i = 0
while i < L:
if str[i]== char:
return 1
i = i + 1
return -1
print(search("S","PYTHON"))
Copy
Output:
>>>
6
-1
>>>
b'Python'
>>>
String Formatting
The format() method is used to perform a string formatting operation. The string
on which this method is called can contain literal text or replacement fields
delimited by braces {}. Each replacement field contains either the numeric index
of a positional argument or the name of a keyword argument.
Syntax:
str.format(*args, **kwargs)
Returns a copy of the string where each replacement field is replaced with the
string value of the corresponding argument.
Contents:
Basic formatting
Value conversion
Numbers
Padding numbers
Signed numbers
Named placeholders
Datetime
Basic formatting:
Example-1:
>>> '{} {}'.format('Python', 'Format')
'Python Format'
>>>
Copy
>>> '{} {}'.format(10, 30)
'10 30'
>>>
Copy
This following statement allows re-arrange the order of display without changing
the arguments.
Example-2:
>>> '{1} {0}'.format('Python', 'Format')
'Format Python'
>>>
Copy
Value conversion:
In %-style you usually use %s for the string representation but there is %r for a
repr(...) conversion.
Setup:
class Data(object):
def __str__(self):
return 'str'
def __repr__(self):
return 'repr'
Example-1:
class Data(object):
def __str__(self):
return 'str'
def __repr__(self):
return 'repr'
x='{0!s} {0!r}'.format(Data())
print (x)
Copy
Output:
str repr
In Python 3 there exists an additional conversion flag that uses the output of
repr(...) but uses ascii(...) instead.
Example-2:
class Data(object):
def __repr__(self):
return 'räpr'
x='{0!r} {0!a}'.format(Data())
print(x)
Copy
Output:
räpr r\xe4pr
Padding and aligning strings:
A value can be padded to a specific length. See the following examples where
the value '15' is encoded as part of the format string.
Example:
Align right:
>>> '{:>15}'.format('Python')
' Python'
>>>
Copy
Align left:
>>> '{:15}'.format('Python')
'Python '
>>>
Copy
By argument:
In the previous example, the value '15' is encoded as part of the format string. It
is also possible to supply such values as an argument.
Example:
>>> '{:<{}s}'.format('Python', 15)
'Python '
>>>
Copy
In the following example we have used '*' as a padding character.
Example:
>>> '{:*<15}'.format('Python')
'Python*********'
>>>
Copy
Align center:
Example:
>>> '{:^16}'.format('Python')
' Python '
>>>
Copy
Truncating long strings:
In the following example, we have truncated ten characters from the left side of a
specified string.
Example:
>>> '{:.10}'.format('Python Tutorial')
'Python Tut'
>>>
Copy
By argument:
Example:
>>> '{:.{}}'.format('Python Tutorial', 10)
'Python Tut'
>>>
Copy
Combining truncating and padding
Example:
>>> '{:10.10}'.format('Python')
'Python '
>>>
Copy
Numbers:
Integers:
>>> '{:d}'.format(24)
'24'
>>>
Copy
Floats:
>>> '{:f}'.format(5.12345678123)
'5.123457'
>>>
Copy
Padding numbers:
Example-1:
>>> '{:5d}'.format(24)
' 24'
>>>
Copy
The padding value represents the length of the complete output for floating
points. In the following example '{:05.2f}' will display the float using five
characters with two digits after the decimal point.
Example-2:
>>> '{:05.2f}'.format(5.12345678123)
'05.12'
>>>
Copy
Signed numbers:
By default only negative numbers are prefixed with a sign, but you can display
numbers prefixed with the positive sign also.
Example-1:
>>> '{:+d}'.format(24)
'+24'
>>>
Copy
You can use a space character to indicate that negative numbers (should be
prefixed with a minus symbol) and a leading space should be used for positive
numbers.
Example-2:
>>> '{: d}'.format((- 24))
'-24'
>>>
Copy
Example-3:
>>> '{: d}'.format(24)
' 24'
>>>
Copy
You can control the position of the sign symbol relative to the padding.
Example-4:
>>> '{:=6d}'.format((- 24))
'- 24'
>>>
Copy
Named placeholders:
Example-1:
>>> data = {'first': 'Place', 'last': 'Holder!'}
>>> '{first} {last}'.format(**data)
'Place Holder!'
>>>
Copy
.format() method can accept keyword arguments.
Example-2:
>>> '{first} {last}'.format(first='Place', last='Holder!')
'Place Holder!'
>>>
Copy
Datetime:
You can format and print datetime object as per your requirement.
Example:
>>> from datetime import datetime
'2016-07-26 03:57'
>>>
Python: strftime()
Last update on February 28 2020 12:08:53 (UTC/GMT +8 hours)
strftime()
The strftime() function returns a string representing the date, controlled by an
explicit format string. Format codes referring to hours, minutes or seconds will
see 0 values.
Syntax:
date.strftime(format)
Complete list of formatting with examples:
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2019-08-28 14:25:35.711200\n"
]
}
],
"source": [
"from datetime import datetime\n",
"now = datetime.now()\n",
"print(now)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %a : Weekday as locale’s abbreviated name.<br>\n",
"Example:<br>\n",
"Sun, Mon, …, Sat (en_US);<br>\n",
"So, Mo, …, Sa (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Weekday as locale’s abbreviated name: Wed\n"
]
}
],
"source": [
"day = now.strftime(\"%a\") \n",
"print(\"Weekday as locale’s abbreviated name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %A : Weekday as locale’s full name<br>\n",
"Example:<br>\n",
"Sunday, Monday, …, Saturday (en_US);<br>\n",
"Sonntag, Montag, …, Samstag (de_DE)<br>"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Weekday as locale’s full name: Wednesday\n"
]
}
],
"source": [
"day = now.strftime(\"%A\") \n",
"print(\"Weekday as locale’s full name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %w: Weekday as a decimal number, where 0 is Sunday and 6 is
Saturday.<br>\n",
"Example:<br>\n",
"0, 1, …, 6"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Weekday as a decimal number: 3\n"
]
}
],
"source": [
"day = now.strftime(\"%w\") \n",
"print(\"Weekday as a decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %d: Day of the month as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"01, 02, …, 31"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Day of the month as a zero-padded decimal number: 28\n"
]
}
],
"source": [
"day = now.strftime(\"%d\") \n",
"print(\"Day of the month as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %b: Month as locale’s abbreviated name.<br>\n",
"Example:<br>\n",
"Jan, Feb, …, Dec (en_US);<br>\n",
"Jan, Feb, …, Dez (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Month as locale's abbreviated name: Aug\n"
]
}
],
"source": [
"day = now.strftime(\"%b\") \n",
"print(\"Month as locale's abbreviated name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %B: Month as locale’s full name.<br>\n",
"Example: <br>\n",
"January, February, …, December (en_US);<br>\n",
"Januar, Februar, …, Dezember (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Month as locale's full Name: August\n"
]
}
],
"source": [
"day = now.strftime(\"%B\") \n",
"print(\"Month as locale's full Name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %m: Month as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"01, 02, …, 12"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Month as a zero-padded decimal number: 08\n"
]
}
],
"source": [
"day = now.strftime(\"%m\") \n",
"print(\"Month as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %y: Year without century as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"00, 01, …, 99"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Year without century as a zero-padded decimal number: 19\n"
]
}
],
"source": [
"day = now.strftime(\"%y\") \n",
"print(\"Year without century as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %Y: Year with century as a decimal number.<br>\n",
"Example:<br>\n",
"0001, 0002, …, 2013, 2014, …, 9998, 9999"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Year with century as a decimal number: 2019\n"
]
}
],
"source": [
"day = now.strftime(\"%Y\") \n",
"print(\"Year with century as a decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %H: Hour (24-hour clock) as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"00, 01, …, 23"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hour as a zero-padded decimal number: 14\n"
]
}
],
"source": [
"day = now.strftime(\"%H\") \n",
"print(\"Hour as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %I: Hour (12-hour clock) as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"01, 02, …, 12"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hour as a zero-paddes decimal number: 02\n"
]
}
],
"source": [
"day = now.strftime(\"%I\") \n",
"print(\"Hour as a zero-paddes decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %p: Locale’s equivalent of either AM or PM.<br>\n",
"Example:<br>\n",
"AM, PM (en_US);<br>\n",
"am, pm (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Locale's equivalent of either AM Or PM: PM\n"
]
}
],
"source": [
"day = now.strftime(\"%p\") \n",
"print(\"Locale's equivalent of either AM Or PM:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %M: Minute as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"00, 01, …, 59"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Minute as a zero-padded decimal number: 25\n"
]
}
],
"source": [
"day = now.strftime(\"%M\") \n",
"print(\"Minute as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %S: Second as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"00, 01, …, 59"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Second as a zero-padded decimal number: 35\n"
]
}
],
"source": [
"day = now.strftime(\"%S\") \n",
"print(\"Second as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %f: Microsecond as a decimal number, zero-padded on the
left.<br>\n",
"Example:<br>\n",
"000000, 000001, …, 999999"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Microsecond as a decimal number, zero-padded on the left: 711200\n"
]
}
],
"source": [
"day = now.strftime(\"%f\") \n",
"print(\"Microsecond as a decimal number, zero-padded on the left:\",
day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %z: UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if
the object is naive).<br>\n",
"Example:<br>\n",
"(empty), +0000, -0400, +1030, +063415, -030712.345216"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"UTC offset in the form ±HHMM[SS[.ffffff]]: +0100\n"
]
}
],
"source": [
"import time\n",
"from datetime import time, tzinfo, timedelta\n",
"class TZ1(tzinfo):\n",
" def utcoffset(self, dt):\n",
" return timedelta(hours=1)\n",
" def dst(self, dt):\n",
" return timedelta(0)\n",
" def tzname(self,dt):\n",
" return \"+01:00\"\n",
" def __repr__(self):\n",
" return f\"{self.__class__.__name__}()\"\n",
"t = time(10, 8, 55, tzinfo=TZ1())\n",
"day = t.strftime(\"%z\") \n",
"print(\"UTC offset in the form ±HHMM[SS[.ffffff]]:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %Z: Time zone name (empty string if the object is naive).<br>\n",
"Example:<br>\n",
"(empty), UTC, EST, CST"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Time zone name: +01:00\n"
]
}
],
"source": [
"import time\n",
"from datetime import time, tzinfo, timedelta\n",
"class TZ1(tzinfo):\n",
" def utcoffset(self, dt):\n",
" return timedelta(hours=1)\n",
" def dst(self, dt):\n",
" return timedelta(0)\n",
" def tzname(self,dt):\n",
" return \"+01:00\"\n",
" def __repr__(self):\n",
" return f\"{self.__class__.__name__}()\"\n",
"t = time(10, 8, 55, tzinfo=TZ1())\n",
"day = t.strftime(\"%Z\")\n",
"print(\"Time zone name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %j: Day of the year as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"001, 002, …, 366"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Day of the year as a zero-padded decimal number: 240\n"
]
}
],
"source": [
"day = now.strftime(\"%j\") \n",
"print(\"Day of the year as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %U: Week number of the year (Sunday as the first day of the week)
as a zero padded decimal number.<br> All days in a new year preceding the
first Sunday are considered to be in week 0.<br>\n",
"Example:<br>\n",
"00, 01, …, 53"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Week number of the year as a zero-padded decimal number: 34\n"
]
}
],
"source": [
"day = now.strftime(\"%U\") \n",
"print(\"Week number of the year as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %W: Week number of the year (Monday as the first day of the week)
as a decimal number.<br> All days in a new year preceding the first Monday are
considered to be in week 0.<br>\n",
"Example:<br>\n",
"00, 01, …, 53 "
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Week number of the year as a zero-padded decimal number: 34\n"
]
}
],
"source": [
"day = now.strftime(\"%W\") \n",
"print(\"Week number of the year as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %c: Locale’s appropriate date and time representation.<br>\n",
"Example:<br>\n",
"Tue Aug 16 21:30:00 1988 (en_US);<br>\n",
"Di 16 Aug 21:30:00 1988 (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Locale's appropriate date and time representation: Wed Aug 28 14:25:35
2019\n"
]
}
],
"source": [
"day = now.strftime(\"%c\") \n",
"print(\"Locale's appropriate date and time representation:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %x: Locale’s appropriate date representation.<br>\n",
"Example:<br>\n",
"08/16/88 (None);<br>\n",
"08/16/1988 (en_US);<br>\n",
"16.08.1988 (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Locale's appropriate date representation: 08/28/19\n"
]
}
],
"source": [
"day = now.strftime(\"%x\") \n",
"print(\"Locale's appropriate date representation:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %X: Locale’s appropriate time representation.<br>\n",
"Example:<br>\n",
"21:30:00 (en_US);<br>\n",
"21:30:00 (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Locale's appropriate time representation: 14:25:35\n"
]
}
],
"source": [
"day = now.strftime(\"%X\") \n",
"print(\"Locale's appropriate time representation:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %%: A literal '%' character.<br>\n",
"Example:<br>\n",
"%"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"A literal '%' character: %\n"
]
}
],
"source": [
"day = now.strftime(\"%%\") \n",
"print(\"A literal '%' character:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Several additional directives not required by the C89 standard are
included for convenience.<br> These parameters all correspond to ISO 8601 date
values. These may not be available on all platforms when used with the
strftime() method.<br> The ISO 8601 year and ISO 8601 week directives are not
interchangeable with the year and week number directives above.<br> Calling
strptime() with incomplete or ambiguous ISO 8601 directives will raise a
ValueError."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %G: ISO 8601 year with century representing the year that contains
the greater part of the ISO week (%V).<br>\n",
"Example:<br>\n",
"0001, 0002, …, 2013, 2014, …, 9998, 9999"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ISO 8601 year with century representing the year that contains the
greater part of the ISO week: 2019\n"
]
}
],
"source": [
"day = now.strftime(\"%G\") \n",
"print(\"ISO 8601 year with century representing the year that contains
the greater part of the ISO week:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %u: ISO 8601 weekday as a decimal number where 1 is
Monday.<br>\n",
"Example:<br>\n",
"1, 2, …, 7"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ISO 8601 weekday as a decimal number where 1 is Monday: 3\n"
]
}
],
"source": [
"from datetime import datetime\n",
"now = datetime.now()\n",
"day = now.strftime(\"%u\") \n",
"print(\"ISO 8601 weekday as a decimal number where 1 is Monday:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %V: ISO 8601 week as a decimal number with Monday as the first day
of the week. Week 01 is the week containing Jan 4.<br>\n",
"Example:<br>\n",
"01, 02, …, 53"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ISO 8601 week as a decimal number with Monday as the first day of the
week.: 35\n"
]
}
],
"source": [
"day = now.strftime(\"%V\") \n",
"print(\"ISO 8601 week as a decimal number with Monday as the first day of
the week.:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"New in version 3.6: %G, %u and %V were added."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Python List
Last update on February 28 2020 12:07:32 (UTC/GMT +8 hours)
List
A list is a container which holds comma-separated values (items or elements)
between square brackets where items or elements need not all have the same
type.
In general, we can define a list as an object that contains multiple data items
(elements). The contents of a list can be changed during program execution. The
size of a list can also change during execution, as elements are added or
removed from it.
Note: There are much programming languages which allow us to create arrays,
which are objects similar to lists. Lists serve the same purpose as arrays and
have many more built-in capabilities. Traditional arrays can not be created in
Python.
Examples of lists:
Contents:
List commands
List indices
Remove the item at the given position in the list, and return it
Return the index in the list of the first item whose value is x
Lists: Commands
<list> = <list>[from_inclusive : to_exclusive : ±step_size]
<list>.append(<el>)
# Or: <list> += [<el>]
<list>.extend(<collection>)
# Or: <list> += <collection>
<list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)
sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1],
el[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, x: out * x,
<collection>)
list_of_chars = list(<str>)
>>> print(my_list1)
>>>
Copy
Following list contains all string:
>>> my_list2 = ['red', 'blue', 'black', 'white'] # the list contains all string
values
>>> print(my_list2)
>>>
Copy
Following list contains a string, an integer and a float values:
>>> my_list3 = ['red', 12, 112.12] # the list contains a string, an integer and
a float values
>>> print(my_list3)
>>>
Copy
A list without any element is called an empty list. See the following statements.
>>> my_list=[]
>>> print(my_list)
[]
>>>
Copy
Use + operator to create a new list that is a concatenation of two lists and use *
operator to repeat a list. See the following statements.
>>> color_list1 = ["White", "Yellow"]
>>> print(color_list)
>>> print(number[0]*4)
>>> print(number*4)
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>>
Copy
List indices
List indices work the same way as string indices, list indices start at 0. If an index
has a positive value it counts from the beginning and similarly it counts backward
if the index has a negative value. As positive integers are used to index from the
left end and negative integers are used to index from the right end, so every item
of a list gives two alternatives indices. Let create a list called color_list with four
items.
color_list=["RED", "Blue", "Green", "Black"]
If you give any index value which is out of range then interpreter creates an error
message. See the following statements.
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements
'Red'
Red Black
'Black'
>>>
Copy
>>> print(color_list)
>>> color_list.append("Yellow")
>>> print(color_list)
>>>
Copy
>>> print(color_list)
>>> print(color_list)
>>>
Copy
>>> print(color_list)
>>> print(color_list)
>>>
Copy
>>> print(color_list)
>>> color_list.remove("Black")
>>> print(color_list)
Copy
>>> print(color_list)
>>> color_list.clear()
>>> print(color_list)
[]
>>>
Copy
List Slices
Lists can be sliced like strings and other sequences.
Syntax:
sliced_list = List_Name[startIndex:endIndex]
This refers to the items of a list starting at index startIndex and stopping just
before index endIndex. The default values for list are 0 (startIndex) and the end
(endIndex) of the list. If you omit both indices, the slice makes a copy of the
original list.
['Red', 'Blue']
>>>
Copy
Cut second item from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements
>>> print(color_list[1:2])
['Blue']
>>> print(color_list[1:-2])
['Blue']
>>>
Copy
Cut second and third elements from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements
>>> print(color_list[1:-1])
['Blue', 'Green']
>>>
Copy
Cut first three items from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements
>>>
Copy
Creates copy of original list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements
>>>
Copy
Remove the item at the given position in the list, and return
it
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]
>>> print(color_list)
'Green'
>>> print(color_list)
>>>
Copy
Return the index in the list of the first item whose value is
x
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]
>>> print(color_list)
>>> color_list.index("Red")
>>> color_list.index("Black")
>>>
Copy
>>> print(color_list)
>>> print(color_list)
>>> color_list.count("Blue")
>>>
Copy
>>> print(color_list)
>>> print(color_list)
>>>
Copy
>>> print(color_list)
>>> print(color_list)
>>>
Copy
>>> print(color_list)
>>> color_list.copy()
>>>
Copy
>>> print(color_list)
>>> color_list.index("Green")
>>>
Copy
>>> print(color_list[0])
Red
>>> print(color_list)
>>> print(color_list[0])
White
>>>
Copy
>>> print(listx)
[1, 2, 3, 4]
>>> print(tuplex)
(1, 2, 3, 4)
>>>
Copy
>>> print(listx)
[1, 5, 7, 3, 2, 4, 6]
>>> print(sublist)
[7, 2, 6]
>>> print(sublist)
[1, 3, 6]
>>> print(sublist)
[6, 2]
>>>
Copy
>>> print(listx)
>>> print(max(listx)) # the max() function of built-in allows to know the highest
25
>>> print(min(listx)) #the min() function of built-in allows to know the lowest
>>>
Copy
Compare two lists in Python
>>> listx1, listx2=[3, 5, 7, 9], [3, 5, 7, 9]
True
>>> listx1, listx2=[9, 7, 5, 3], [3, 5, 7, 9] #create two lists equal, but
unsorted.
False
>>> listx1, listx2 =[2, 3, 5, 7], [3, 5, 7, 9] #create two different list
False
True
>>>
Copy
>>> print(listx)
>>> print(listx)
World
>>> print(listx)
>>> listx[1][2]=4
>>> print(listx)
>>>
Copy
list?
>>> listy = list("HELLO WORLD")
>>> print(listy)
['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']
>>> index = listy.index("L") #get index of the first item whose value is passed
as parameter
>>> print(index)
>>> index = listy.index("L", 4) #define the index from which you want to search
>>> print(index)
>>> print(index)
>>>
Copy
>>> print(color_list)
>>> color_list.append("White")
>>> color_list.append("Yellow")
>>> print(color_list)
>>> color_list.pop()
'Yellow'
>>> color_list.pop()
'White'
>>> color_list.pop()
'Black'
>>> color_list
>>>
Copy
>>> print(color_list)
deque(['Red', 'Blue', 'Green', 'Black', 'White'])
>>> print(color_list)
'Red'
>>> print(color_list)
'Blue'
>>> print(color_list)
>>>
Python Dictionary
Last update on February 28 2020 12:07:03 (UTC/GMT +8 hours)
Dictionary
Python dictionary is a container of the unordered set of objects like lists. The
objects are surrounded by curly braces { }. The items in a dictionary are a
comma-separated list of key:value pairs where keys and values are Python data
type.
Each object or value accessed by key and keys are unique in the dictionary. As
keys are used for indexing, they must be the immutable type (string, number, or
tuple). You can create an empty dictionary using empty curly braces.
Contents :
Dictionary commands
Dictionary: Commands
# Coll. of keys that reflects changes.
<view> = <dict>.keys()
# Coll. of values that reflects changes.
<view> = <dict>.values()
# Coll. of key-value tuples.
<view> = <dict>.items()
<dict>.update(<dict>)
# Creates a dict from coll. of key-value pairs.
<dict> = dict(<collection>)
# Creates a dict from two collections.
<dict> = dict(zip(keys, values))
# Creates a dict from collection of keys.
<dict> = dict.fromkeys(keys [, value])
Counter
>>> new_dict = {}
>>> print(new_dict)
{}
>>> color
>>>
Copy
Get value by key in Python dictionary
>>> #Declaring a dictionary
>>> dict[1]
20.5
>>> dict[3]
23.22
>>> dict.get(1)
20.5
>>> dict.get(3)
23.22
>>>
Copy
Add key/value to a dictionary in Python
>>> #Declaring a dictionary with a single element
>>>print(dic)
{'pdy1': 'DICTIONARY'}
>>> print(dic)
>>>
>>> print(d)
>>> d.update({2:30})
>>> print(d)
>>>
Copy
Iterate over Python dictionaries using for loops
Code:
d = {'Red': 1, 'Green': 2, 'Blue': 3}
Copy
Output:
>>>
Green corresponds to 2
Red corresponds to 1
Blue corresponds to 3
>>>
Remove a key from a Python dictionary
Code:
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myDict)
Copy
Output:
>>>
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
{'d': 4, 'b': 2, 'c': 3}
>>>
Sort a Python dictionary by key
Code:
color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}
Copy
Output:
>>>
black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
>>>
Find the maximum and minimum value of a Python dictionary
Code:
my_dict = {'x':500, 'y':5874, 'z': 560}
Copy
Output:
>>>
Maximum Value: 5874
Minimum Value: 500
>>>
Concatenate two Python dictionaries into a new one
Code:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
print(dic4)
Copy
Output:
>>>
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
>>>
Test whether a Python dictionary contains a specific key
Code:
fruits = {}
fruits["apple"] = 1
fruits["mango"] = 2
fruits["banana"] = 4
# Use in.
if "mango" in fruits:
print("Has mango")
else:
print("No mango")
if "orange" in fruits:
print("Has orange")
else:
print("No orange")
Copy
Output
>>>
Has mango
No orange
>>>
Find the length of a Python dictionary
Code:
fruits = {"mango": 2, "orange": 6}
# Use len() function to get the length of the dictionary
print("Length:", len(fruits))
Copy
Output:
>>>
Length: 2
>>>
Python Tuples
Last update on February 28 2020 12:16:21 (UTC/GMT +8 hours)
Tuples
A tuple is a container which holds a series of comma-separated values (items or
elements) between parentheses such as an (x, y) co-ordinate. Tuples are like
lists, except they are immutable (i.e. you cannot change its content once created)
and can hold mix data types. Tuples play a sort of "struct" role in Python -- a
convenient way to pass around a little logical, fixed size bundle of values.
Contents:
Tuple commands
Create a tuple
List to tuple
Clone a tuple
In Python how to know the number of times an item has repeated
Slice a tuple
Tuple: Commands
To create a tuple, just list the values within parenthesis separated by commas.
The "empty" tuple is just an empty pair of parenthesis
>>> #create an empty tuple
>>> tuplex = ()
()
>>> tuplex = 4, 7, 3, 8, 1
(4, 7, 3, 8, 1)
>>> tuplex = 4,
(4,)
()
(True, False)
>>>
Copy
How to get an item of the tuple in Python?
>>> #create a tuple
>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
>>> print(tuplex)
>>> print(item)
>>> print(item1)
>>>
Copy
How to know if an element exists within a tuple in Python?
>>> #create a tuple
>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
>>> print(tuplex)
True
False
>>>
Copy
List to tuple
>>> #create list
>>> print(listx)
[5, 10, 7, 4, 15, 3]
>>> #use the tuple() function built-in Python, passing as parameter the list
>>> print(tuplex)
>>>
Copy
Unpack a tuple in several variables
>>> #create a tuple
>>> tuplex = 4, 8, 3
>>> print(tuplex)
(4, 8, 3)
15
>>> #the number of variables must be equal to the number of items of the tuple
>>>
Copy
Add item in Python tuple!
>>> #create a tuple
>>> print(tuplex)
(4, 6, 2, 8, 3, 1)
>>> #tuples are immutable, so you can not add new elements
>>> #using merge of tuples with the + operator you can add an element and it will
create a new tuple
>>> print(tuplex)
(4, 6, 2, 8, 3, 1, 9)
>>> print(tuplex)
>>> listx.append(30)
>>> print(tuplex)
>>>
Copy
Clone a tuple
>>> from copy import deepcopy
>>> print(tuplex)
>>> tuplex_clone[2].append(50)
>>> print(tuplex_clone)
>>> print(tuplex)
>>>
Copy
In Python how to know the number of times an item has repeated
>>> #create a tuple
>>> tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
>>> print(tuplex)
(2, 4, 5, 6, 2, 3, 4, 4, 7)
>>> print(count)
>>> print(count)
>>>
Copy
Remove an item from a tuple
>>> #create a tuple
>>> print(tuplex)
('w', 3, 'd', 'r', 'e', 's', 'l')
>>> #using merge of tuples with the + operator you can remove an item and it will
create a new tuple
>>> print(tuplex)
>>> listx.remove("l")
>>> print(tuplex)
>>>
Copy
Slice a tuple
>>> #create a tuple
>>> #used tuple[start:stop] the start index is inclusive and the stop index
#is exclusive.
>>> print(_slice)
(5, 4)
>>> #if the start index isn't defined, is taken from the beg inning of the tuple.
>>> print(_slice)
(2, 4, 3, 5, 4, 6)
>>> #if the end index isn't defined, is taken until the end of the tuple
>>> print(_slice)
(6, 7, 8, 6, 1)
>>> print(_slice)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
>>> print(_slice)
(3, 5, 4, 6)
>>>
Copy
Find the index of an item of the tuple
>>> #create a tuple
>>> print(tuplex)
('i', 'n', 'd', 'e', 'x', ' ', 't', 'u', 'p', 'l', 'e')
>>> #get index of the first item whose value is passed as parameter
>>> print(index)
>>> print(index)
8
>>> #define the segment of the tuple to be searched
>>> print(index)
>>> #if item not exists in the tuple return ValueError Exception
>>>
Copy
The size of a tuple
>>> tuplex = tuple("w3resource") #create a tuple
>>> print(tuplex)
('w', '3', 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')
>>> print(len(tuplex))
10
>>>
Copy
How operators + and * are used with a Python tuple?
>>> #create a tuple
>>> print(tuplex * 6)
(5, 5, 5, 5, 5, 5)
>>> tuplex2 = ("w", 3, "r", "s", "o", "u", "r", "c", "e")
>>> #The + operator allow create a tuple joining two or more tuples
>>> print(tuplex)
(3, 6, 9, 12, 15, 'w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e', True, False)
>>>
Copy
Slice of a tuple using step parameter
>>> #create a tuple
>>> print(tuplex)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
>>> #step specify an increment between the elements to cut of the tuple.
>>> print(_slice)
>>> print(_slice)
>>> print(_slice)
('L', ' ')
>>> print(_slice)
>>>
Copy
Modify items of a tuple
>>> #create a tuple
>>> print(tuplex)
>>> #tuples are immutable, so you can not modify items which are also immutable, as
str, boolean, numbers etc.
>>> tuplex[3].append(200)
>>> print(tuplex)
>>>
Copy
Previous: Python Dictionary
Python Sets
Last update on February 28 2020 12:08:08 (UTC/GMT +8 hours)
Sets
A set object is an unordered collection of distinct hashable objects. It is
commonly used in membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union, difference,
and symmetric difference.
Sets support x in the set, len(set), and for x in set like other collections. Set is an
unordered collection and does not record element position or order of insertion.
Sets do not support indexing, slicing, or other sequence-like behavior.
There are currently two built-in set types, set, and frozenset. The set type is
mutable - the contents can be changed using methods like add() and remove().
Since it is mutable, it has no hash value and cannot be used as either a
dictionary key or as an element of another set. The frozenset type is immutable
and hashable - its contents cannot be altered after it is created; it can, therefore,
be used as a dictionary key or as an element of another set.
Contents:
Set commands
Intersection of sets
Union of sets
Symmetric difference
Clear sets
Set: Commands
<set> = set()
<set>.add(<el>)
# Or: <set> |= {<el>}
<set>.update(<collection>)
# Or: <set> |= <set>
<set> = <set>.union(<coll.>)
# Or: <set> | <set>
<set> = <set>.intersection(<coll.>)
# Or: <set> & <set>
<set> = <set>.difference(<coll.>)
# Or: <set> - <set>
<set> = <set>.symmetric_difference(<coll.>)
# Or: <set> ^ <set>
<bool> = <set>.issubset(<coll.>)
# Or: <set> <= <set>
<bool> = <set>.issuperset(<coll.>)
# Or: <set> >= <set>
<el> = <set>.pop()
# Raises KeyError if empty.
<set>.remove(<el>)
# Raises KeyError if missing.
<set>.discard(<el>)
# Doesn't raise an error.
Frozen Set
>>> print(setx)
set()
>>> print(n)
{0, 1, 2, 3, 4, 5}
>>>
Copy
print(n)
>>>
Copy
>>> color_set.add("Red")
>>> print(color_set)
{'Red'}
>>> #Add multiple items
>>> print(color_set)
>>>
Copy
pop() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])
>>> num_set.pop()
>>> print(num_set)
{1, 2, 3, 4, 5}
>>> num_set.pop()
>>> print(num_set)
{2, 3, 4, 5}
>>>
Copy
remove() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])
>>> num_set.remove(0)
>>> print(num_set)
{1, 2, 3, 4, 5}
>>>
Copy
discard() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])
>>> num_set.discard(3)
>>> print(num_set)
{0, 1, 2, 4, 5}
>>>
Copy
Intersection of sets:
In mathematics, the intersection A ∩ B of two sets A and B is the set that
contains all elements of A that also belong to B (or equivalently, all elements of B
that also belong to A), but no other elements.
>>> #Intersection
>>> print(setz)
{'blue'}
>>>
Copy
Union of sets:
In set theory, the union (denoted by ∪) of a collection of sets is the set of all
distinct elements in the collection. It is one of the fundamental operations through
which sets can be combined and related to each other.
>>> #Union
>>>
Copy
Set difference:
>>> setx = set(["green", "blue"])
>>> print(setz)
{'blue'}
>>> print(setb)
{'green'}
>>>
Copy
Symmetric difference:
>>> setx = set(["green", "blue"])
>>> print(setc)
{'yellow', 'green'}
>>>
Copy
>>> print(issubset)
False
>>> print(issuperset)
False
>>>
Copy
More Example:
>>> setx = set(["green", "blue"])
>>> print(issubset)
True
>>> print(issuperset)
True
>>>
Copy
>>> print(setd)
{'blue', 'green'}
>>>
Copy
Clear sets:
>>> setx = set(["green", "blue"])
>>> sete.clear()
>>> print(sete)
set()
>>>
Introduction
In all programming and scripting language, a function is a block of program
statements which can be used repetitively in a program. It saves the time of a
developer. In Python concept of function is same as in other languages. There
are some built-in functions which are part of Python. Besides that, we can
defines functions according to our need.
In Python, a user-defined function's declaration begins with the keyword def and followed by
the function name.
The function may take arguments(s) as input within the opening and closing parentheses,
just after the function name followed by a colon.
After defining the function name and arguments(s) a block of program statement(s) start at
the next line and these statement(s) must be indented.
Syntax:
def function_name(argument1, argument2, ...) :
statement_1
statement_2
....
Inside Function Call
<function>(<positional_args>)
# f(0, 0)
<function>(<keyword_args>)
# f(x=0, y=0)
<function>(<positional_args>, <keyword_args>)
# f(0, y=0)
Syntax:
function_name(arg1, arg2)
Argument combinations:
def f(a, b, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, b=3) | f(1, 2, 3)
def f(*, a, b, c): # f(a=1, b=2, c=3)
def f(a, *, b, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3)
def f(a, b, *, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, c=3)
avg_number(3, 4)
Copy
Output:
Average of 3 and 4 is 3.5
Explanation:
def function_name() :
statement_1
statement_2
....
Example:
def printt():
printt()
Copy
Output:
This is Python 3.2 Tutorial
This is Python 3.2 Tutorial
This is Python 3.2 Tutorial
Explanation:
function_name(arg1, arg2)
Example:
The following function returns the square of the sum of two numbers.
def nsquare(x, y):
Copy
Output:
The square of the sum of 2 and 3 is : 25
Explanation:
Example:
The following function returns the square of the sum of two numbers, where
default value of the second argument is 2.
def nsquare(x, y = 2):
Copy
Output:
The square of the sum of 2 and 2 is: 16
The square of the sum of 2 and 4 is : 36
Explanation:
Keyword Arguments:
We have already learned how to use default arguments values, functions can
also be called using keyword arguments. Arguments which are preceded with a
variable name followed by a '=' sign (e.g. var_name=") are called keyword
arguments.
All the keyword arguments passed must match one of the arguments accepted
by the function. You may change the order of appearance of the keyword. See
the following example.
Example:
def marks(english, math = 85, science = 80):
marks(71, 77)
Copy
Output:
Marks in : English is - 71 , Math - 77 , Science - 80
Marks in : English is - 65 , Math - 85 , Science - 74
Marks in : English is - 75 , Math - 90 , Science - 70
Explanation:
Line 1: The function named marks has three parameters, there is no default
value in the first parameter (english) but remaining parameters have default
values (math = 85, science = 80).
Line 3: The parameter english gets the value of 71, math gets the value 77 and
science gets the default value of 80.
Line 4: The parameter english gets the value of 65, math gets the default value of
85 and science gets the value of 74 due to keyword arguments.
Line 5: Here we use three keyword arguments and the parameter english gets
the value 75, math gets the value 90 and science gets the value 70.
Example:
def sum(*numbers):
s = 0
for n in numbers:
s += n
return s
print(sum(1,2,3,4))
Copy
Output:
10
Lambda Forms:
return (x + y)/2
print(average(4, 3))
Copy
may also be defined using lambda
Copy
Output:
3.5
Python Documentation Strings
Docstring Conventions :
- String literal literals must be enclosed with a triple quote. Docstring should be
informative
- The first line may briefly describe the object's purpose. The line should begin
with a capital letter and ends with a dot.
- If a documentation string is a muti-line string then the second line should be
blank followed by any detailed explanation starting from the third line.
"""
Copy
Python Module
Last update on February 28 2020 12:07:50 (UTC/GMT +8 hours)
Introduction
Modules are a simple way to organize a program which contains program code,
variables etc.. All these definitions and statements are contained in a single
Python file. The name of the module is the name of the file name with .py
extension. Modules are not loaded unless we execute in Python interpreter or
call within a program. In Python, there are modules in a standard library, current
directory or directories containing .py files (in fact each file with .py extension is a
module). To define a module, you can use Python IDLE, Notepad++ or any
suitable text editor. Lets create a file called factorial.py which will create the
factorial (in mathematics, the factorial of n [a positive integer] is the product of all
positive integers less than or equal to n.) of a positive integer as well as some
other jobs in the current directory.
Example:
# factorial.py
while n>0:
fact *= n
n=n-1
if(n<=1):
break
return
return fact
result = []
while n>0:
result.append(n)
n = n - 1
if(n==0):
break
return
return result
Copy
Importing a module:
In order to use a module, use import statement. Go to the Python interpreter and
execute the following command :
from..import statement
from .. import statement is used to import selective names(s) or all names that a
module defines. See the following codes.
def factcal(n):
fact = 1
while n>0:
fact *= n
n=n-1
if(n<=1):
break
else:
return
print(fact)
result = []
while n>0:
result.append(n)
n = n - 1
if(n==0):
break
else:
return
print(result)
if __name__ == "__main__":
import sys
factcal(int(sys.argv[1]))
factdata(int(sys.argv[2]))
Copy
Now execute the file at the command prompt (here in windows).
Modules Path:
in PYTHONPATH (a list of directory names), default search path for module files.
PYTHONPATH is an environment variable. You will get it using 'env' command in UNIX-
based operating system or in the properties of My Computer in windows system.
Standard Module:
Python has many standard modules as a library. These are aimed to add
efficiency or to access operating system primitives. Some of the modules depend
upon the operating system.
sys is a Python Standard module which is very useful. It is built into every Python
interpreter.
The built-in function dir() is used to get the names (a sorted list of strings), a
module is defined. Check it into Python shell.
Python Calendar
This module allows you to output calendars like the Unix cal program and
provides additional useful functions related to the calendar. By default, these
calendars have Monday as the first day of the week, and Sunday as the last (the
European convention). Use setfirstweekday() to set the first day of the week to
Sunday (6) or to any other weekday. Parameters that specify dates are given as
integers. For related functionality, see also the datetime and time modules.
Calender:
Name Description
iterweekdays() method Return an iterator for the weekdays numbers that will be used for one week.
itermonthdates() method The itermonthdates() method is used to return an iterator for the month month (1
itermonthdays2() method The itermonthdays2() method is used to return an iterator for the month month in
itermonthdays() method The itermonthdays() method is used to return an iterator for the month month in
monthdatescalendar() method The monthdatescalendar() method is used to return a list of the weeks in the mon
of seven datetime.date objects.
monthdays2calendar() method The monthdays2calendar() method is used to return a list of the weeks in the mon
of seven tuples of day numbers and weekday numbers.
monthdayscalendar() method The monthdayscalendar() method is used to return a list of the weeks in the mont
of seven day numbers.
yeardatescalendar() method The yeardatescalendar() method is used to return the data for the specified year r
month rows.
yeardays2calendar() method The yeardays2calendar() method is used to return the data for the specified year r
yeardatescalendar()).
yeardayscalendar() method The yeardayscalendar() method is used to return the data for the specified year re
text-calendar-formatmonth() The formatmonth() method is used to return a month’s calendar in a multi-line str
method
text-calendar-prmonth() method The prmonth() method is used to Print a month’s calendar as returned by formatm
text-calendar-formatyear() method The formatyear() method is used to return a m-column calendar for an entire year
text-calendar-pryear() method The pryear() method is used to Print the calendar for an entire year as returned by
html-calendar-formatmonth() The formatmonth() method is used to return a month’s calendar as an HTML table
method
html-calendar-formatyear()method The formatyear() method is used to return a year’s calendar as an HTML table.
setfirstweekday() method Sets the weekday (0 is Monday, 6 is Sunday) to start each week.
firstweekday() method The firstweekday() method is used to returns the current setting for the weekday
isleap() method The isleap() method is used to returns True if year is a leap year, otherwise False.
leapdays() method The leapdays() method is used to returns the number of leap years in the range fro
weekday() method The weekday() method is used to returns the day of the week (0 is Monday) for ye
weekheader() method The weekheader() method is used to return a header containing abbreviated week
one weekday.
monthrange() method The monthrange() method is used to returns weekday of first day of the month an
and month.
monthcalendar() method The monthrange() method is used to returns a matrix representing a month’s cale
prmonth() method The prmonth() method is used to prints a month’s calendar as returned by month
month() method The month() method is used to returns a month’s calendar in a multi-line string us
prcal() method The prcal() method is used to prints the calendar for an entire year as returned by
calendar() method The calendar() method is used to returns a 3-column calendar for an entire year as
TextCalendar class.
iterweekdays() method
The iterweekdays() method returns an iterator for the weekday numbers that will
be used for one week. The first number from the iterator will be the same as the
number returned by firstweekday().
Syntax
iterweekdays()
Example -1: Python iterweekdays() method
import calendar
#set firstweekday=0
cal= calendar.Calendar(firstweekday=0)
for x in cal.iterweekdays():
print(x)
Copy
Output:
0
1
2
3
4
5
6
Example - 2: iterweekdays() method
import calendar
#set firstweekday=1
cal= calendar.Calendar(firstweekday=1)
for x in cal.iterweekdays():
print(x)
Copy
Output:
1
2
3
4
5
6
0
Note: firstweekday() - Return an array for one week of weekday numbers starting
with the configured first one.
iterweekdays() method
The iterweekdays() method returns an iterator for the weekday numbers that will
be used for one week. The first number from the iterator will be the same as the
number returned by firstweekday().
Syntax
iterweekdays()
Example -1: Python iterweekdays() method
import calendar
#set firstweekday=0
cal= calendar.Calendar(firstweekday=0)
for x in cal.iterweekdays():
print(x)
Copy
Output:
0
1
2
3
4
5
6
Example - 2: iterweekdays() method
import calendar
#set firstweekday=1
cal= calendar.Calendar(firstweekday=1)
for x in cal.iterweekdays():
print(x)
Copy
Output:
1
2
3
4
5
6
0
Note: firstweekday() - Return an array for one week of weekday numbers starting
with the configured first one.
Python Calendar Module: itermonthdays2()
method
Last update on February 28 2020 12:40:29 (UTC/GMT +8 hours)
itermonthdays2() method
The itermonthdays2() method is used to get an iterator for the month in the year
similar to itermonthdates(). Days returned will be tuples consisting of a day
number and a week day number.
Syntax
itermonthdays2(year, month)
Parameters
Name Description
cal= calendar.Calendar()
print(x)
Copy
Output:
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(1, 6)
(2, 0)
(3, 1)
(4, 2)
(5, 3)
(6, 4)
(7, 5)
(8, 6)
(9, 0)
(10, 1)
(11, 2)
(12, 3)
(13, 4)
(14, 5)
(15, 6)
(16, 0)
(17, 1)
(18, 2)
(19, 3)
(20, 4)
(21, 5)
(22, 6)
(23, 0)
(24, 1)
(25, 2)
(26, 3)
(27, 4)
(28, 5)
(29, 6)
(30, 0)
(31, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(0, 6)
Note: itermonthdates
Return an iterator for the month month (1-12) in the year year. This iterator will
return all days (as datetime.date objects) for the month and all days before the
start of the month or after the end of the month that are required to get a
complete week.
Python Calendar Module: itermonthdays()
method
Last update on February 28 2020 12:40:36 (UTC/GMT +8 hours)
itermonthdays() method
The itermonthdays() method returns an iterator of a specified month and a year.
Days returned will simply be day numbers. The method is similar to
itermonthdates().
Syntax:
itermonthdays(year, month)
Parameters:
Name Description
cal= calendar.Calendar()
print(x)
Copy
Output:
0
0
0
0
0
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
0
0
0
0
0
Note: itermonthdates: Return an iterator for the month month (1-12) in the year
year. This iterator will return all days (as datetime.date objects) for the month and
all days before the start of the month or after the end of the month that are
required to get a complete week.
Other resource : https://www.w3resource.com/python/module/calendar/itermonthdays.php
Python Classes
Last update on February 28 2020 12:14:18 (UTC/GMT +8 hours)
Introduction
The basic idea behind an object-oriented programming (OOP) is to combine both
data and associated procedures (known as methods) into a single unit which
operate on the data. Such a unit is called an object.
We have already worked with some objects in Python, (See Python data type
chapter) for example strings, lists are objects defined by the string and list
classes which are available by default into Python. Let's declare two objects a
string and a list and test their type with type() function.
Local Variables:
def function_local(a):
a = 50
a = 100
function_local(40)
print('Value of a is ->',a)
Copy
Output:
a is -> 40
After new value within the function a is -> 50
Value of a is -> 100
Explanation:
global statement:
def function_local():
global a
a = 50
a = 100
function_local()
print('Value of a is ->',a)
Copy
Output:
a is -> 100
After new value within the function a is -> 50
Value of a is -> 50
Explanation:
Line No.- 3 : The variable 'a' is declared as a global variable, therefore the value
of a is now 100.
Line No.- 5 : Assign the value 50 to 'a' and it will hold same value inside and
outside the function unless we assign a new value.
nonlocal statement
a = 10
def inside():
a = 20
print("Inside a ->", a)
inside()
print("outside a->", a)
outside()
Copy
In the above example the first print() statement simply print the value of 'a', which
is 20 as 'a' is local within inside() function. The second print() statement prints the
value 'a', which is 10 as the inside() function has no effect. Now we introduce a
nonlocal statement in inside() function and the code will be:
def outside():
a = 10
def inside():
nonlocal a
a = 20
inside()
outside()
Copy
The second print() statement prints the value 'a', which is 20 as the variable 'a' is
rebound..
- For example 'a' maps to [1, 2, 3] or 'a' maps to the value 25.
- The built-in namespace is created when Python interpreter starts and is never
deleted.
- The global namespace for a module is created when the module is called and
last until the interpreter quits.
- The local namespace for a function is created when the function is called and
deleted when the function returns.
Defining a class:
In object oriented programming classes and objects are the main features. A
class creates a new data type and objects are instances of a class which follows
the definition given inside the class. Here is a simple form of class definition.
class Student:
Statement-1
Statement-1
....
....
....
Statement-n
A class definition started with the keyword 'class' followed by the name of the
class and a colon.
When a class definition is entered, a new namespace is created, and used as the
local scope.
Creating a Class:
Here we create a simple class using class keyword followed by the class name
(Student) which follows an indented block of segments (student class, roll no.,
name).
#studentdetails.py
class Student:
stu_class = 'V'
stu_roll_no = 12
stu_name = "David"
Copy
Class Objects:
There are two kind of operations class objects supports : attribute references and
instantiation. Attribute references use the standard syntax, obj.name for all
attribute references in Python. Therefore if the class definition (add a method in
previous example) look like this
#studentdetails1.py
class Student:
stu_class = 'V'
stu_roll_no = 12
stu_name = "David"
def messg(self):
Copy
__doc__ is also a valid attribute which returns the docstring of the class.
__init__ method:
There are many method names in Python which have special importance. A
class may define a special method named __init__ which does some initialization
work and serves as a constructor for the class. Like other functions or methods
__init__ can take any number of arguments. The __init__ method is run as soon
as an object of a class is instantiated and class instantiation automatically
invokes __init__() for the newly-created class instance. See the following
example a new, initialized instance can be obtained by:
#studentdetailsinit.py
class Student:
self.c = sclass
self.r = sroll
self.n = sname
def messg(self):
Copy
Operators
Addition:
class School:
self.subjects = list(subjects)
class Subject:
F1 + F2
Copy
Output:
<__main__.School object at 0x0000000008B82470>
from pathlib import Path
path.absolute()
Copy
Output:
WindowsPath('C:/Users/User/AppData/Local/Programs/Python/Python37
/data')
Greater / Equality:
class Person:
'''person entity'''
self.first_name = first_name
self.surname = surname
self.age = age
def __repr__(self):
data = [
print(results)
Copy
Output:
[Person(first_name=John, surname=Smith, age=13),
Person(first_name=Anne, surname=McNell, age=11),
Person(first_name=Mary, surname=Brown, age=14)]
Length:
class School:
self.subjects = list(subjects)
def __len__(self):
return len(self.subjects)
print(len(Sub))
Copy
Output:
2
Getitem:
class School:
self.subjects = list(subjects)
print(Sub[0])
Copy
Output:
<__main__.Subject object at 0x0000000007ACC5F8>
Inheritance:
Example:
In a company Factory, staff and Office staff have certain common properties - all
have a name, designation, age etc. Thus they can be grouped under a class
called CompanyMember. Apart from sharing those common features, each
subclass has its own characteristic - FactoryStaff gets overtime allowance while
OfficeStaff gets traveling allowance for an office job. The derived classes
( FactoryStaff & OfficeStaff) has its own characteristic and, in addition, they
inherit the properties of the base class (CompanyMember). See the example
code.
# python-inheritance.py
class CompanyMember:
self.name = name
self.designation = designation
self.age = age
def tell(self):
'''Details of an employee.'''
class FactoryStaff(CompanyMember):
self.overtime_allow = overtime_allow
CompanyMember.tell(self)
class OfficeStaff(CompanyMember):
self.marks = travelling_allow
CompanyMember.tell(self)
Copy
Now execute the class in Python Shell and see the output.
Built-in Functions
The Python interpreter has a number of functions and types built into it that are
always available. They are listed here in alphabetical order.
Name Description
abs() The abs() function is used to get the absolute (positive) value of a given number.
all() The all() function is used to test whether all elements of an iterable are true or not.
any() The any() function returns True if any element of the iterable is true. The function returns False if the i
ascii() The ascii() function returns a string containing a printable representation (escape the non-ASCII charac
bin() The bin() function is used to convert an integer number to a binary string. The result is a valid Python e
callable() The callable() function returns True if the object argument appears callable, False if not.
chr() The chr() function returns the string representing a character whose Unicode codepoint is the integer.
classmethod() The classmethod() function is used to convert a method into a class method.
complie() The compile() function is used to compile the source into a code.
complex() The complex() function is used to create a complex number or convert a string or number to a comple
delattr() The delattr() function is used to delete the specified attribute from the specified object.
dir() The dir() function returns all properties and methods of the specified object, without the values. The f
even built-in properties which are default for all object.
divmod() The divmod() function takes two non complex numbers as arguments and return a pair of numbers co
using integer division. With mixed operand types, the rules for binary arithmetic operators apply.
enumerate() The enumerate() function returns an enumerate object. iterable must be a sequence, an iterator, or so
eval() The eval() function is used to evaluate the specified expression. If the expression is a correct Python st
exec() The exec() function is used to execute the specified Python code. object must be either a string or a co
filter() The filter() function construct an iterator from those elements of iterable for which function returns tr
float() The float() function is used to convert the specified value into a floating point number.
format() The format() function is used to format a specified value into a specified format.
frozenset() The frozenset() function returns a new frozenset object, optionally with elements taken from iterable.
getattr() The getattr() function returns the value of the named attribute of object and name must be a string
globals() The globals() function returns a dictionary representing the current global symbol table.
hash() The hash() function returns the hash value of the object (if it has one).
help() The help() function is used to execute the built-in help system.
hex() The hex() function converts an integer number to a lowercase hexadecimal string prefixed with "0x".
input() The input() function allows user input. If the prompt argument is present, it is written to standard outp
int() The int() function converts the specified value into an integer number.
isinstance() The isinstance() function returns true if the object argument is an instance of the classinfo argument, o
issubclass() The issubclass() function returns true if the specified object is a subclass of the specified object, otherw
list() The list() function is used to create a list object (list is actually a mutable sequence type).
locals() The locals() function is used to get the local symbol table as a dictionary. Free variables are returned b
not in class blocks.
map() The map() function is used to execute a specified function for each item in a inerrable.
max() The max() function is used to find the item with the largest value in an iterable.
memoryview() The memoryview() function is used to get a memory view object from a specified object.
min() The min() function is used to find the item with the smallest value in an iterable.
next() The next() function is used to get the next item in an iterator.
oct() The oct() function is used to convert an integer number to an octal string.
open() The open() function is used to open a file and returns it as a file object.
ord() The ord() function is used to get an integer representing the Unicode code point of that character.
pow() The pow() function is used to get the value of x to the power of y (xy). If z is present, return x to the po
pow(x, y) % z).
print() The print() function is used to print objects to the text stream file, separated by sep and followed by e
keyword arguments.
range() The range() function is used to get a sequence of numbers, starting from 0 by default, and increments
repr() The repr() function returns a string containing a printable representation of an object.
round() The round() function returns the rounded floating point value number, rounded to ndigits digits after t
to zero.
setattr() The setattr() function is used to set the value of the specified attribute of the specified object.
slice() The slice() function is used to get a slice object representing the set of indices specified by range(start,
sorted() The sorted() function is used to get a new sorted list from the items in iterable.
str() The str() function is used to convert the specified value into a string.
sum() The sum() function is used to get the sum of all items in an iterable.
tuple() The tuple() function is used to create a tuple in Python. Iterable may be a sequence, a container that s
vars The vars() function is used to get the __dict__ attribute of the given object.
zip() The zip() function is used to make an iterator that aggregates elements from each of the iterables.
https://www.w3resource.com/python/built-in-function/abs.php
Module Index
Name Description
base64 RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85
binascii Tools for converting between binary and various ASCII-encoded binary.
cgi Helpers for running Python scripts via the Common Gateway Interface.
compileall Tools for byte-compiling all Python source files in a directory tree.
cProfile This function takes a single argument that can be passed to the exec() function, and an o
executes:
csv Write and read tabular data to and from delimited files.
map() The map() function is used to execute a specified function for each item in a inerrable.
.email Package supporting the parsing, manipulating, and generating email messages.
ensurepip Bootstrapping the "pip" installer into an existing Python installation or virtual environme
enum The repr() function returns a string containing a printable representation of an object.
filecmp The setattr() function is used to set the value of the specified attribute of the specified o
ftplib The sum() function is used to get the sum of all items in an iterable.
gzip Interfaces for gzip compression and decompression using file objects.
linecache This module provides random access to individual lines from text files.
marshal Convert Python objects to streams of bytes and back (with different constraints).
pickletools Contains extensive comments about the pickle protocols and pickle-machine opcodes, a
platform pkgutil
posix(Umix The most common POSIX system calls (normally used via module os).
quopri Encode and decode files using the MIME quoted-printable encoding.
rlcompleter Python identifier completion, suitable for the GNU readline library.
runpy Locate and run Python modules without importing them first.
stat Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().
statistics mathematical statistics functions
Python API
Top-level functions
xlwings.view(obj, sheet=None)
Opens a new workbook and displays an object on its first sheet by default. If you
provide a sheet object, it will clear the sheet before displaying the object on the
existing sheet.
Examples
>>> import xlwings as xw
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
>>> xw.view(df)
New in version 0.7.1.
Object model
Apps
classxlwings.main.Apps(impl)
A collection of all app objects:
add()
Creates a new App. The new App becomes the active one. Returns an App object.
count
keys()
Provides the PIDs of the Excel instances that act as keys in the Apps collection.
App
classxlwings.App(visible=None, spec=None, add_book=True, impl=None)
An app corresponds to an Excel instance. New Excel instances can be fired up like
so:
>>> xw.apps
Apps([<Excel App 1668>, <Excel App 1644>])
>>> xw.apps[1668] # get the available PIDs via xw.apps.keys()
<Excel App 1668>
>>> xw.apps.active
<Excel App 1668>
On Mac, while xlwings allows you to run multiple instances of Excel, it’s a feature
that is not officially supported by Excel for Mac: Unlike on Windows, Excel will
not ask you to open a read-only version of a file if it is already open in another
instance. This means that you need to watch out yourself so that the same file is
not being overwritten from different instances.
activate(steal_focus=False)
Activates the Excel app.
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
books
calculate()
calculation
Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> wb.app.calculation = 'manual'
display_alerts
The default value is True. Set this property to False to suppress prompts and alert
messages while code is running; when a message requires a response, Excel
chooses the default response.
kill()
macro(name)
Runs a Sub or Function in Excel VBA that are not part of a specific workbook but
e.g. are part of an add-in.
Examples
Function MySum(x, y)
MySum = x + y
End Function
pid
quit()
range(cell1, cell2=None)
Range object from the active sheet of the active book, see Range() .
screen_updating
Turn screen updating off to speed up your script. You won’t be able to see what
the script is doing, but it will run faster. Remember to set the screen_updating
property back to True when your script ends.
selection
startup_path
Returns the path to XLSTART which is where the xlwings add-in gets copied to by
doing xlwings addin install .
status_bar
Gets or sets the value of the status bar. Returns False if Excel has control of it.
version
Examples
>>> import xlwings as xw
>>> xw.App().version
VersionNumber('15.24')
>>> xw.apps[10559].version.major
15
Changed in version 0.9.0.
visible
Gets or sets the visibility of Excel to True or False .
Books
classxlwings.main.Books(impl)
A collection of all book objects:
active
add()
Creates a new Book. The new Book becomes the active Book. Returns a Book
object.
open(fullname, update_links=None, read_only=None, format=None, password=None, write_
res_password=None, ignore_read_only_recommended=None, origin=None, delimiter=None,
editable=None, notify=None, converter=None, add_to_mru=None, local=None, corrupt_load
=None)
Opens a Book if it is not open yet and returns it. If it is already open, it doesn’t
raise an exception but simply returns the Book object.
Returns: Book
Book
classxlwings.Book(fullname=None, update_links=None, read_only=None, format=None, password
=None, write_res_password=None, ignore_read_only_recommended=None, origin=None, delimiter=
None, editable=None, notify=None, converter=None, add_to_mru=None, local=None, corrupt_load=
None, impl=None)
A book object is a member of the books collection:
>>> app = xw.App() # or something like xw.apps[10559] for existing apps, get the PIDs
via xw.apps.keys()
>>> app.books['Book1']
xw.Book xw.books
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
app
classmethodcaller()
References the calling book when the Python function is called from Excel
via RunPython . Pack it into the function being called from Excel, e.g.:
import xlwings as xw
def my_macro():
wb = xw.Book.caller()
wb.sheets[0].range('A1').value = 1
close()
fullname
Returns the name of the object, including its path on disk, as a string. Read-only
String.
macro(name)
Examples
Function MySum(x, y)
MySum = x + y
End Function
can be accessed like this:
name
names
Returns a names collection that represents all the names in the specified book
(including all sheet-specific names).
save(path=None)
Saves the Workbook. If a path is being provided, this works like SaveAs() in Excel.
If no path is specified and if the file hasn’t been saved previously, it’s being saved
in the current working directory with the current filename. Existing files are
overwritten without prompting.
Parameters path (str or path-like object, default None) – Full path to the
: workbook
Example
>>> import xlwings as xw
>>> wb = xw.Book()
>>> wb.save()
>>> wb.save(r'C:\path\to\new_file_name.xlsx')
New in version 0.3.1.
selection
set_mock_caller()
Sets the Excel file which is used to mock xw.Book.caller() when the code is called
from Python and not from Excel via RunPython .
Examples
# This code runs unchanged from Excel via RunPython and from Python directly
import os
import xlwings as xw
def my_macro():
sht = xw.Book.caller().sheets[0]
sht.range('A1').value = 'Hello xlwings!'
if __name__ == '__main__':
xw.Book('file.xlsm').set_mock_caller()
my_macro()
sheets
Returns a sheets collection that represents all the sheets in the book.
Sheets
classxlwings.main.Sheets(impl)
A collection of all sheet objects:
active
Returns the active Sheet.
add(name=None, before=None, after=None)
Sheet
classxlwings.Sheet(sheet=None, impl=None)
A sheet object is a member of the sheets collection:
activate()
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
autofit(axis=None)
Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> wb.sheets['Sheet1'].autofit('c')
>>> wb.sheets['Sheet1'].autofit('r')
>>> wb.sheets['Sheet1'].autofit()
New in version 0.2.3.
book
cells
Returns a Range object that represents all the cells on the Sheet (not just the cells
that are currently in use).
charts
See Charts
clear()
clear_contents()
Clears the content of the whole sheet but leaves the formatting.
delete()
index
name
Gets or sets the name of the Sheet.
names
Returns a names collection that represents all the sheet-specific names (names
defined with the “SheetName!” prefix).
pictures
See Pictures
range(cell1, cell2=None)
Returns a Range object from the active sheet of the active book, see Range() .
select()
shapes
See Shapes
used_range
Returns:
Return
xw.Range
type:
Examples
Active Sheet:
import xlwings as xw
xw.Range('A1')
xw.Range('A1:C3')
xw.Range((1,1))
xw.Range((1,1), (3,3))
xw.Range('NamedRange')
xw.Range(xw.Range('A1'), xw.Range('B2'))
Specific Sheet:
xw.books['MyBook.xlsx'].sheets[0].range('A1')
add_hyperlink(address, text_to_display=None, screen_tip=None)
address
Returns a string value that represents the range reference. Use get_address() to
be able to provide paramaters.
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
autofit()
clear()
clear_contents()
color
To set the color, either use an RGB tuple (0, 0, 0) or a color constant. To remove
the background, set the color to None , see Examples.
Returns: RGB
Return
tuple
type:
Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1').color = (255,255,255)
>>> xw.Range('A2').color
(255, 255, 255)
>>> xw.Range('A2').color = None
>>> xw.Range('A2').color is None
True
New in version 0.3.0.
column
Returns the number of the first column in the in the specified range. Read-only.
Returns:
Return
Integer
type:
column_width
Gets or sets the width, in characters, of a Range. One unit of column width is
equal to the width of one character in the Normal style. For proportional fonts,
the width of the character 0 (zero) is used.
If all columns in the Range have the same width, returns the width. If columns in
the Range have different widths, returns None.
Note: If the Range is outside the used range of the Worksheet, and columns in
the Range have different widths, returns the width of the first column.
Returns:
Return
float
type:
columns
Returns a RangeColumns object that represents the columns in the specified range.
New in version 0.9.0.
copy(destination=None)
Returns:
Return
None
type:
count
current_region
This property returns a Range object representing a range bounded by (but not
including) any combination of blank rows and blank columns or the edges of the
worksheet. It corresponds to Ctrl-* on Windows and Shift-Ctrl-Space on Mac.
Returns:
Return
Range object
type:
delete(shift=None)
shift (str, default None) – Use left or up . If omitted, Excel decides based
Parameters:
on the shape of the range.
Returns:
Return
None
type:
end(direction)
Returns a Range object that represents the cell at the end of the region that
contains the source range. Equivalent to pressing Ctrl+Up, Ctrl+down, Ctrl+left, or
Ctrl+right.
Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1:B2').value = 1
>>> xw.Range('A1').end('down')
<Range [Book1]Sheet1!$A$2>
>>> xw.Range('B2').end('right')
<Range [Book1]Sheet1!$B$2>
expand(mode='table')
Expands the range according to the mode provided. Ignores empty top-left cells
(unlike Range.end() ).
Returns:
Return
Range
type:
Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1').value = [[None, 1], [2, 3]]
>>> xw.Range('A1').expand().address
$A$1:$B$2
>>> xw.Range('A1').expand('right').address
$A$1:$B$1
New in version 0.9.0.
formula
formula_array
get_address(row_absolute=True, column_absolute=True, include_sheetname=False, exter
nal=False)
Returns the address of the range in the specified format. address can be used
instead if none of the defaults need to be changed.
Returns:
Return
type: str
Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range((1,1)).get_address()
'$A$1'
>>> xw.Range((1,1)).get_address(False, False)
'A1'
>>> xw.Range((1,1), (3,3)).get_address(True, False, True)
'Sheet1!A$1:C$3'
>>> xw.Range((1,1), (3,3)).get_address(True, False, external=True)
'[Book1]Sheet1!A$1:C$3'
height
Returns:
Return
float
type:
hyperlink
Returns the hyperlink address of the specified Range (single Cell only)
Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1').value
'www.xlwings.org'
>>> xw.Range('A1').hyperlink
'http://www.xlwings.org'
insert(shift=None, copy_origin='format_from_left_or_above')
Returns:
Return
type: None
last_cell
Returns:
Return
Range
type:
Example
>>> import xlwings as xw
>>> wb = xw.Book()
>>> rng = xw.Range('A1:E4')
>>> rng.last_cell.row, rng.last_cell.column
(4, 5)
New in version 0.3.5.
left
Returns the distance, in points, from the left edge of column A to the left edge of
the range. Read-only.
Returns:
Return
float
type:
merge(across=False)
Parameters across (bool, default False) – True to merge cells in each row of the
: specified Range as separate merged cells.
merge_area
Returns a Range object that represents the merged Range containing the
specified cell. If the specified cell isn’t in a merged range, this property returns the
specified cell.
merge_cells
Returns True if the Range contains merged cells, otherwise False
name
number_format
Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1').number_format
'General'
>>> xw.Range('A1:C3').number_format = '0.00%'
>>> xw.Range('A1:C3').number_format
'0.00%'
New in version 0.2.3.
offset(row_offset=0, column_offset=0)
Returns a Range object that represents a Range that’s offset from the specified
range.
options(convert=None, **options)
Allows you to set a converter and their options. Converters define how Excel
Ranges and their values are being converted both during reading and writing
operations. If no explicit converter is specified, the base converter is being
applied, see Converters and Options.
Keyword Arguments:
ndim (int, default None) – number of dimensions
numbers (type, default None) – type of numbers, e.g. int
dates (type, default None) – e.g. datetime.date defaults
to datetime.datetime
empty (object, default None) – transformation of empty cells
transpose (Boolean, default False) – transpose values
expand (str, default None) –
Returns:
Return
type: Range object
paste(paste=None, operation=None, skip_blanks=False, transpose=False)
Retu
rns:
Retu None
rn
type
:
raw_value
Gets and sets the values directly as delivered from/accepted by the engine that is
being used ( pywin32 or appscript ) without going through any of xlwings’ data
cleaning/converting. This can be helpful if speed is an issue but naturally will be
engine specific, i.e. might remove the cross-platform compatibility.
resize(row_size=None, column_size=None)
Return
type: Range
row
Returns the number of the first row in the specified range. Read-only.
Returns:
Return
Integer
type:
row_height
Gets or sets the height, in points, of a Range. If all rows in the Range have the
same height, returns the height. If rows in the Range have different heights,
returns None.
Note: If the Range is outside the used range of the Worksheet, and rows in the
Range have different heights, returns the height of the first row.
Returns:
Return
float
type:
rows
Returns a RangeRows object that represents the rows in the specified range.
select()
shape
sheet
size
top
Returns the distance, in points, from the top edge of row 1 to the top edge of the
range. Read-only.
Returns:
Return
float
type:
unmerge()
value
Returns: object
width
Returns:
Return
float
type:
RangeRows
classxlwings.RangeRows(rng)
rng = xw.Range('A1:C4')
rng.rows[0].value = 'a'
for r in rng.rows:
print(r.address)
autofit()
count
RangeColumns
classxlwings.RangeColumns(rng)
Example
import xlwings as xw
rng = xw.Range('A1:C4')
rng.columns[0].value = 'a'
for c in rng.columns:
print(c.address)
autofit()
count
Shapes
classxlwings.main.Shapes(impl)
A collection of all shape objects on the specified sheet:
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
count
Shape
classxlwings.Shape(*args, **options)
The shape object is a member of the shapes collection:
activate()
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
delete()
height
Returns or sets the number of points that represent the height of the shape.
left
Returns or sets the number of points that represent the horizontal position of the
shape.
name
parent
scale_height(factor, relative_to_original_size=False, scale='scale_from_top_left')
factor :float
relative_to_original_size :bool, optional
If False , it scales relative to current height (default). For True must be a picture or OLE
object.
scale :str, optional
One of scale_from_top_left (default), scale_from_bottom_right , scale_from_middle
scale_width(factor, relative_to_original_size=False, scale='scale_from_top_left')
factor :float
scale :str, optional
One of scale_from_top_left (default), scale_from_bottom_right , scale_from_middle
top
Returns or sets the number of points that represent the vertical position of the
shape.
type
width
Returns or sets the number of points that represent the width of the shape.
Charts
classxlwings.main.Charts(impl)
A collection of all chart objects on the specified sheet:
add(left=0, top=0, width=355, height=211)
Returns:
Return
type: Chart
Examples
>>> import xlwings as xw
>>> sht = xw.Book().sheets[0]
>>> sht.range('A1').value = [['Foo1', 'Foo2'], [1, 2]]
>>> chart = sht.charts.add()
>>> chart.set_source_data(sht.range('A1').expand())
>>> chart.chart_type = 'line'
>>> chart.name
'Chart1'
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
count
Chart
classxlwings.Chart(name_or_index=None, impl=None)
The chart object is a member of the charts collection:
chart_type
Returns and sets the chart type of the chart.
delete()
height
Returns or sets the number of points that represent the height of the chart.
left
Returns or sets the number of points that represent the horizontal position of the
chart.
name
parent
set_source_data(source)
top
Returns or sets the number of points that represent the vertical position of the
chart.
width
Returns or sets the number of points that represent the width of the chart.
Pictures
classxlwings.main.Pictures(impl)
A collection of all picture objects on the specified sheet:
add(image, link_to_file=False, save_with_document=True, left=0, top=0, width=None, heigh
t=None, name=None, update=False, scale=1)
Returns:
Return
type: Picture
Examples
1. Picture
count
Picture
classxlwings.Picture(impl=None)
The picture object is a member of the pictures collection:
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
delete()
height
Returns or sets the number of points that represent the height of the picture.
left
Returns or sets the number of points that represent the horizontal position of the
picture.
New in version 0.5.0.
name
parent
top
Returns or sets the number of points that represent the vertical position of the
picture.
update(image)
Replaces an existing picture with a new one, taking over the attributes of the
existing picture.
width
Returns or sets the number of points that represent the width of the picture.
Names
classxlwings.main.Names(impl)
A collection of all name objects in the workbook:
add(name, refers_to)
Returns:
Return
type: Name
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
count
Name
classxlwings.Name(impl)
The name object is a member of the names collection:
api
Returns the native object ( pywin32 or appscript obj) of the engine being used.
New in version 0.9.0.
delete()
name
refers_to
Returns or sets the formula that the name is defined to refer to, in A1-style
notation, beginning with an equal sign.
refers_to_range
UDF decorators
xlwings.func(category="xlwings", volatile=False, call_in_wizard=True)
Functions decorated with xlwings.func will be imported as Function to Excel when
running “Import Python UDFs”.
xlwings.sub()
Functions decorated with xlwings.sub will be imported as Sub (i.e. macro) to Excel
when running “Import Python UDFs”.
xlwings.arg(arg, convert=None, **options)
Apply converters and options to arguments, see also Range.options() .
Examples:
import xlwings as xw
import numpy as np
@xw.func
@xw.arg('x', np.array, ndim=2)
def add_one(x):
return x + 1
xlwings.ret(convert=None, **options)
Apply converters and options to return values, see also Range.options() .
Examples
import pandas as pd
@xw.func
@xw.ret(index=False, header=False)
def get_dataframe(n, m):
return pd.DataFrame(np.arange(n * m).reshape((n, m)))
2. Dynamic array:
Note
If your version of Excel supports the new native dynamic arrays, then you don’t
have to do anything special, and you shouldn’t use the expand decorator! To check
if your version of Excel supports it, see if you have the =UNIQUE() formula
available. Native dynamic arrays were introduced in Office 365 Insider Fast at the
end of September 2018.
expand='table' turns the UDF into a dynamic array. Currently you must not use
Unlike standard Excel arrays, dynamic arrays are being used from a single cell like
a standard function and auto-expand depending on the dimensions of the
returned array:
import xlwings as xw
import numpy as np
@xw.func
@xw.ret(expand='table')
def dynamic_array(n, m):
return np.arange(n * m).reshape((n, m))
New in version 0.10.0.
Reports
xlwings.pro.reports.create_report(template, output, book_settings=None, app=None, **dat
a)
This feature requires xlwings PRO .
Writes the values of all key word arguments to the output file according to
the template and the variables contained in there (Jinja variable syntax). Following
variable types are supported:
strings, numbers, lists, simple dicts, NumPy arrays, Pandas DataFrames, PIL Image
objects that have a filename and Matplotlib figures.
template (str) – Path to your Excel template,
e.g. r'C:\Path\to\my_template.xlsx'
output (str) – Path to your Report,
e.g. r'C:\Path\to\my_report.xlsx'
book_settings (dict, default None) – A dictionary
of xlwings.Book parameters, for details see: xlwings.Book . For
example: book_settings={'update_links': False} .
Parameters:
app (xlwings App, default None) – By passing in an xlwings
App instance, you can control where your report runs and
configure things like visible=False . For details
see xlwings.App . By default, it creates the report in the
currently active instance of Excel.
data (kwargs) – All key/value pairs that are used in the
template.
Returns: wb
Return
type: xlwings Book
Examples
With many template variables it may be useful to collect the data first:
REST API
New in version 0.13.0.
Quickstart
xlwings offers an easy way to expose an Excel workbook via REST API both on Windows
and macOS. This can be useful when you have a workbook running on a single computer
and want to access it from another computer. Or you can build a Linux based web app
that can interact with a legacy Excel application while you are in the progress of
migrating the Excel functionality into your web app (if you need help with that, give us a
shout).
You can run the REST API server from a command prompt or terminal as follows (this
requires Flask>=1.0, so make sure to pip install Flask ):
$ curl "http://127.0.0.1:5000/book/book1/sheets/0/range/A1:B2"
{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 10.0,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"1",
"2"
],
[
"3",
"4"
]
],
"formula_array": null,
"height": 32.0,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": "General",
"row": 1,
"row_height": 16.0,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
1.0,
2.0
],
[
3.0,
4.0
]
],
"width": 130.0
}
In the command prompt where your server is running, press Ctrl-C to shut it down
again.
The xlwings REST API is a thin wrapper around the Python API which makes it very easy
if you have worked previously with xlwings. It also means that the REST API does
require the Excel application to be up and running which makes it a great choice if the
data in your Excel workbook is constantly changing as the REST API will always deliver
the current state of the workbook without the need of saving it first.
Note
Currently, we only provide the GET methods to read the workbook. If you are also
interested in the POST methods to edit the workbook, let us know via GitHub issues.
Some other things will also need improvement, most notably exception handling.
Run the server
xlwings restapi run will run a Flask development server on http://127.0.0.1:5000. You
can provide --host and --port as command line args and it also respects the Flask
environment variables like FLASK_ENV=development .
If you want to have more control, you can run the server directly with Flask, see
the Flask docs for more details:
set FLASK_APP=xlwings.rest.api
flask run
If you are on Mac, use export FLASK_APP=xlwings.rest.api instead
of set FLASK_APP=xlwings.rest.api .
For production, you can use any WSGI HTTP Server like gunicorn (on Mac)
or waitress (on Mac/Windows) to serve the API. For example, with gunicorn you would
do: gunicorn xlwings.rest.api:api . Or with waitress (adjust the host accordingly if you
want to make the api accessible from outside of localhost):
Indexing
While the Python API offers Python’s 0-based indexing (e.g. xw.books[0] ) as well as
Excel’s 1-based indexing (e.g. xw.books(1) ), the REST API only offers 0-based indexing,
e.g. /books/0 .
Range Options
The REST API accepts Range options as query parameters,
see xlwings.Range.options() e.g.
/book/book1/sheets/0/range/A1?expand=table&transpose=true
Endpoint overview
Endpoi Correspond
Short Description
nt s to
/book Book Finds your workbook across all open instances of Excel and will open
Endpoi Correspond
Short Description
nt s to
it if it can’t find it
/apps Apps This allows you to specify the Excel instance you want to work with
Endpoint details
/book
GET /book/<fullname_or_name>
Example response:
{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
}
GET /book/<fullname_or_name>/names
Example response:
{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
},
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}
]
}
GET /book/<fullname_or_name>/names/<name>
Example response:
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}
GET /book/<fullname_or_name>/names/<name>/range
Example response:
{
"address": "$A$1",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 1,
"current_region": "$A$1:$B$2",
"formula": "=1+1.1",
"formula_array": "=1+1,1",
"height": 14.25,
"last_cell": "$A$1",
"left": 0.0,
"name": "myname2",
"number_format": "General",
"row": 1,
"row_height": 14.3,
"shape": [
1,
1
],
"size": 1,
"top": 0.0,
"value": 2.1,
"width": 51.0
}
GET /book/<fullname_or_name>/sheets
Example response:
{
"sheets": [
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
},
{
"charts": [],
"name": "Sheet2",
"names": [],
"pictures": [],
"shapes": [],
"used_range": "$A$1"
}
]
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>
Example response:
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/charts
Example response:
{
"charts": [
{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}
]
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/charts/<chart_name_or_ix>
Example response:
{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/names
Example response:
{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}
]
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/names/<sheet_scope_name>
Example response:
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/names/<sheet_scope_name>/range
Example response:
{
"address": "$B$2:$C$3",
"color": null,
"column": 2,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"",
""
],
[
"",
""
]
],
"formula_array": "",
"height": 28.5,
"last_cell": "$C$3",
"left": 51.0,
"name": "Sheet1!myname1",
"number_format": "General",
"row": 2,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 14.25,
"value": [
[
null,
null
],
[
null,
null
]
],
"width": 102.0
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/pictures
Example response:
{
"pictures": [
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}
]
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/pictures/<picture_name_or_ix>
Example response:
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/range
Example response:
{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/range/<address>
Example response:
{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/shapes
Example response:
{
"shapes": [
{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
},
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"type": "picture",
"width": 100.0
}
]
}
GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/shapes/<shape_name_or_ix>
Example response:
{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
}
/books
GET /books
Example response:
{
"books": [
{
"app": 1104,
"fullname": "Book1",
"name": "Book1",
"names": [],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1"
]
},
{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
},
{
"app": 1104,
"fullname": "Book4",
"name": "Book4",
"names": [],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1"
]
}
]
}
GET /books/<book_name_or_ix>
Example response:
{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
}
GET /books/<book_name_or_ix>/names
Example response:
{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
},
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}
]
}
GET /books/<book_name_or_ix>/names/<name>
Example response:
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}
GET /books/<book_name_or_ix>/names/<name>/range
Example response:
{
"address": "$A$1",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 1,
"current_region": "$A$1:$B$2",
"formula": "=1+1.1",
"formula_array": "=1+1,1",
"height": 14.25,
"last_cell": "$A$1",
"left": 0.0,
"name": "myname2",
"number_format": "General",
"row": 1,
"row_height": 14.3,
"shape": [
1,
1
],
"size": 1,
"top": 0.0,
"value": 2.1,
"width": 51.0
}
GET /books/<book_name_or_ix>/sheets
Example response:
{
"sheets": [
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
},
{
"charts": [],
"name": "Sheet2",
"names": [],
"pictures": [],
"shapes": [],
"used_range": "$A$1"
}
]
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>
Example response:
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/charts
Example response:
{
"charts": [
{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}
]
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/charts/<chart_name_or_ix>
Example response:
{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names
Example response:
{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}
]
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names/<sheet_scope_name>
Example response:
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names/<sheet_scope_name>/range
Example response:
{
"address": "$B$2:$C$3",
"color": null,
"column": 2,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"",
""
],
[
"",
""
]
],
"formula_array": "",
"height": 28.5,
"last_cell": "$C$3",
"left": 51.0,
"name": "Sheet1!myname1",
"number_format": "General",
"row": 2,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 14.25,
"value": [
[
null,
null
],
[
null,
null
]
],
"width": 102.0
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/pictures
Example response:
{
"pictures": [
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}
]
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/pictures/<picture_name_or_ix>
Example response:
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/range
Example response:
{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/range/<address>
Example response:
{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/shapes
Example response:
{
"shapes": [
{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
},
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"type": "picture",
"width": 100.0
}
]
}
GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/shapes/<shape_name_or_ix>
Example response:
{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
}
/apps
GET /apps
Example response:
{
"apps": [
{
"books": [
"Book1",
"C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"Book4"
],
"calculation": "automatic",
"display_alerts": true,
"pid": 1104,
"screen_updating": true,
"selection": "[Book1.xlsx]Sheet2!$A$1",
"version": "16.0",
"visible": true
},
{
"books": [
"Book2",
"Book5"
],
"calculation": "automatic",
"display_alerts": true,
"pid": 7920,
"screen_updating": true,
"selection": "[Book5]Sheet2!$A$1",
"version": "16.0",
"visible": true
}
]
}
GET /apps/<pid>
Example response:
{
"books": [
"Book1",
"C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"Book4"
],
"calculation": "automatic",
"display_alerts": true,
"pid": 1104,
"screen_updating": true,
"selection": "[Book1.xlsx]Sheet2!$A$1",
"version": "16.0",
"visible": true
}
GET /apps/<pid>/books
Example response:
{
"books": [
{
"app": 1104,
"fullname": "Book1",
"name": "Book1",
"names": [],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1"
]
},
{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
},
{
"app": 1104,
"fullname": "Book4",
"name": "Book4",
"names": [],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1"
]
}
]
}
GET /apps/<pid>/books/<book_name_or_ix>
Example response:
{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
}
GET /apps/<pid>/books/<book_name_or_ix>/names
Example response:
{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
},
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}
]
}
GET /apps/<pid>/books/<book_name_or_ix>/names/<name>
Example response:
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}
GET /apps/<pid>/books/<book_name_or_ix>/names/<name>/range
Example response:
{
"address": "$A$1",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 1,
"current_region": "$A$1:$B$2",
"formula": "=1+1.1",
"formula_array": "=1+1,1",
"height": 14.25,
"last_cell": "$A$1",
"left": 0.0,
"name": "myname2",
"number_format": "General",
"row": 1,
"row_height": 14.3,
"shape": [
1,
1
],
"size": 1,
"top": 0.0,
"value": 2.1,
"width": 51.0
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets
Example response:
{
"sheets": [
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
},
{
"charts": [],
"name": "Sheet2",
"names": [],
"pictures": [],
"shapes": [],
"used_range": "$A$1"
}
]
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>
Example response:
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/charts
Example response:
{
"charts": [
{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}
]
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/charts/<chart_name_
or_ix>
Example response:
{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names
Example response:
{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}
]
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names/<sheet_scope_
name>
Example response:
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names/<sheet_scope_
name>/range
Example response:
{
"address": "$B$2:$C$3",
"color": null,
"column": 2,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"",
""
],
[
"",
""
]
],
"formula_array": "",
"height": 28.5,
"last_cell": "$C$3",
"left": 51.0,
"name": "Sheet1!myname1",
"number_format": "General",
"row": 2,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 14.25,
"value": [
[
null,
null
],
[
null,
null
]
],
"width": 102.0
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/pictures
Example response:
{
"pictures": [
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}
]
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/pictures/<picture_n
ame_or_ix>
Example response:
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/range
Example response:
{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/range/<address>
Example response:
{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/shapes
Example response:
{
"shapes": [
{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
},
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"type": "picture",
"width": 100.0
}
]
}
GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/shapes/<shape_name_
or_ix>
Example response:
{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
}
Previous