0% found this document useful (0 votes)
5 views64 pages

Classes Till String Formating

strings in python

Uploaded by

SirajUlHaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views64 pages

Classes Till String Formating

strings in python

Uploaded by

SirajUlHaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

Python Classes and Objects

❮ PreviousNext ❯

Python Classes/Objects
Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:

ExampleGet your own Python Server


Create a class named MyClass, with a property named x:

class MyClass:
x = 5
Try it Yourself »

Create Object
Now we can use the class named MyClass to create objects:

Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
Try it Yourself »

The __init__() Function


The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.

To understand the meaning of classes we have to understand the built-


in __init__() function.

All classes have a function called __init__(), which is always executed when
the class is being initiated.

Use the __init__() function to assign values to object properties, or other


operations that are necessary to do when the object is being created:

Example
Create a class named Person, use the __init__() function to assign values for
name and age:

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

p1 = Person("John", 36)

print([Link])
print([Link])
Try it Yourself »
Note: The __init__() function is called automatically every time the class is
being used to create a new object.

ADVERTISEMENT
The __str__() Function
The __str__() function controls what should be returned when the class object
is represented as a string.

If the __str__() function is not set, the string representation of the object is
returned:

Example
The string representation of an object WITHOUT the __str__() function:

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

p1 = Person("John", 36)

print(p1)
Try it Yourself »

Example
The string representation of an object WITH the __str__() function:

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def __str__(self):
return f"{[Link]}({[Link]})"

p1 = Person("John", 36)

print(p1)
Try it Yourself »

Object Methods
Objects can also contain methods. Methods in objects are functions that belong
to the object.

Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def myfunc(self):
print("Hello my name is " + [Link])

p1 = Person("John", 36)
[Link]()
Try it Yourself »
Note: The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.

The self Parameter


The self parameter is a reference to the current instance of the class, and is
used to access variables that belong to the class.

It does not have to be named self, you can call it whatever you like, but it has
to be the first parameter of any function in the class:

Example
Use the words mysillyobject and abc instead of self:

class Person:
def __init__(mysillyobject, name, age):
[Link] = name
[Link] = age

def myfunc(abc):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()
Try it Yourself »

Modify Object Properties


You can modify properties on objects like this:

Example
Set the age of p1 to 40:

[Link] = 40
Try it Yourself »

Delete Object Properties


You can delete properties on objects by using the del keyword:

Example
Delete the age property from the p1 object:

del [Link]
Try it Yourself »

Delete Objects
You can delete objects by using the del keyword:

Example
Delete the p1 object:

del p1
Try it Yourself »

The pass Statement


class definitions cannot be empty, but if you for some reason have
a class definition with no content, put in the pass statement to avoid getting
an error.

Example
class Person:
pass

Python Inheritance
❮ PreviousNext ❯

Python Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived
class.

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other
class:

ExampleGet your own Python Server


Create a class named Person, with firstname and lastname properties, and
a printname method:

class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

#Use the Person class to create an object, and then execute the
printname method:

x = Person("John", "Doe")
[Link]()
Try it Yourself »

Create a Child Class


To create a class that inherits the functionality from another class, send the
parent class as a parameter when creating the child class:

Example
Create a class named Student, which will inherit the properties and methods
from the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties
or methods to the class.

Now the Student class has the same properties and methods as the Person
class.

Example
Use the Student class to create an object, and then execute
the printname method:

x = Student("Mike", "Olsen")
[Link]()
Try it Yourself »

ADVERTISEMENT

Add the __init__() Function


So far we have created a child class that inherits the properties and methods
from its parent.

We want to add the __init__() function to the child class (instead of


the pass keyword).

Note: The __init__() function is called automatically every time the class is
being used to create a new object.

Example
Add the __init__() function to the Student class:

class Student(Person):
def __init__(self, fname, lname):
#add properties etc.

When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.

Note: The child's __init__() function overrides the inheritance of the


parent's __init__() function.

To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:

Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Try it Yourself »
Now we have successfully added the __init__() function, and kept the
inheritance of the parent class, and we are ready to add functionality in
the __init__() function.

Use the super() Function


Python also has a super() function that will make the child class inherit all the
methods and properties from its parent:

Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Try it Yourself »

By using the super() function, you do not have to use the name of the parent
element, it will automatically inherit the methods and properties from its parent.

Add Properties
Example
Add a property called graduationyear to the Student class:

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
[Link] = 2019
Try it Yourself »

In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another
parameter in the __init__() function:

Example
Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year

x = Student("Mike", "Olsen", 2019)


Try it Yourself »

Add Methods
Example
Add a method called welcome to the Student class:

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year

def welcome(self):
print("Welcome", [Link], [Link], "to the class
of", [Link])
Try it Yourself »

If you add a method in the child class with the same name as a function in the
parent class, the inheritance of the parent method will be overridden.

Python Iterators
❮ PreviousNext ❯

Python Iterators
An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can
traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator
protocol, which consist of the methods __iter__() and __next__().

Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from.

All these objects have a iter() method which is used to get an iterator:

ExampleGet your own Python Server


Return an iterator from a tuple, and print each value:

mytuple = ("apple", "banana", "cherry")


myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Try it Yourself »

Even strings are iterable objects, and can return an iterator:

Example
Strings are also iterable objects, containing a sequence of characters:

mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

Try it Yourself »
Looping Through an Iterator
We can also use a for loop to iterate through an iterable object:

Example
Iterate the values of a tuple:

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
print(x)
Try it Yourself »

Example
Iterate the characters of a string:

mystr = "banana"

for x in mystr:
print(x)
Try it Yourself »

The for loop actually creates an iterator object and executes


the next() method for each loop.

Create an Iterator
To create an object/class as an iterator you have to implement the
methods __iter__() and __next__() to your object.

As you have learned in the Python Classes/Objects chapter, all classes have a
function called __init__(), which allows you to do some initializing when the
object is being created.

The __iter__() method acts similar, you can do operations (initializing etc.),
but must always return the iterator object itself.
The __next__() method also allows you to do operations, and must return the
next item in the sequence.

Example
Create an iterator that returns numbers, starting with 1, and each sequence will
increase by one (returning 1,2,3,4,5 etc.):

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
Try it Yourself »

StopIteration
The example above would continue forever if you had enough next()
statements, or if it was used in a for loop.

To prevent the iteration from going on forever, we can use


the StopIteration statement.

In the __next__() method, we can add a terminating condition to raise an error


if the iteration is done a specified number of times:

Example
Stop after 20 iterations:
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)

Try it Yourself »

Python Polymorphism
❮ PreviousNext ❯

The word "polymorphism" means "many forms", and in programming it


refers to methods/functions/operators with the same name that can be
executed on many objects or classes.

Function Polymorphism
An example of a Python function that can be used on different objects is
the len() function.

String
For strings len() returns the number of characters:
ExampleGet your own Python Server
x = "Hello World!"

print(len(x))
Try it Yourself »

Tuple
For tuples len() returns the number of items in the tuple:

Example
mytuple = ("apple", "banana", "cherry")

print(len(mytuple))
Try it Yourself »

Dictionary
For dictionaries len() returns the number of key/value pairs in the dictionary:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

print(len(thisdict))

Python Scope
❮ PreviousNext ❯

A variable is only available from inside the region it is created. This is


called scope.
Local Scope
A variable created inside a function belongs to the local scope of that function,
and can only be used inside that function.

ExampleGet your own Python Server


A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)

myfunc()
Try it Yourself »

Function Inside Function


As explained in the example above, the variable x is not available outside the
function, but it is available for any function inside the function:

Example
The local variable can be accessed from a function within the function:

def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

myfunc()
Try it Yourself »

ADVERTISEMENT

Global Scope
A variable created in the main body of the Python code is a global variable and
belongs to the global scope.
Global variables are available from within any scope, global and local.

Example
A variable created outside of a function is global and can be used by anyone:

x = 300

def myfunc():
print(x)

myfunc()

print(x)
Try it Yourself »

Naming Variables
If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global
scope (outside the function) and one available in the local scope (inside the
function):

Example
The function will print the local x, and then the code will print the global x:

x = 300

def myfunc():
x = 200
print(x)

myfunc()

print(x)
Try it Yourself »

Global Keyword
If you need to create a global variable, but are stuck in the local scope, you can
use the global keyword.
The global keyword makes the variable global.

Example
If you use the global keyword, the variable belongs to the global scope:

def myfunc():
global x
x = 300

myfunc()

print(x)
Try it Yourself »

Also, use the global keyword if you want to make a change to a global variable
inside a function.

Example
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:

x = 300

def myfunc():
global x
x = 200

myfunc()

print(x)
Try it Yourself »

Nonlocal Keyword
The nonlocal keyword is used to work with variables inside nested functions.

The nonlocal keyword makes the variable belong to the outer function.

Example
If you use the nonlocal keyword, the variable will belong to the outer function:
def myfunc1():
x = "Jane"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x

print(myfunc1())

Python Modules
❮ PreviousNext ❯

What is a Module?
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file
extension .py:

ExampleGet your own Python Server


Save this code in a file named [Link]

def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule

[Link]("Jonathan")
Run Example »
Note: When using a function from a module, use the
syntax: module_name.function_name.

Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):

Example
Save this code in the file [Link]

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)
Run Example »

ADVERTISEMENT

Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Example
Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)
Run Example »

Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.

Example
Import and use the platform module:

import platform

x = [Link]()
print(x)
Try it Yourself »

Using the dir() Function


There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:

Example
List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)
Try it Yourself »
Note: The dir() function can be used on all modules, also the ones you create
yourself.

Import From Module


You can choose to import only parts from a module, by using the from keyword.

Example
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Run Example »
Note: When importing using the from keyword, do not use the module name
when referring to elements in the module.
Example: person1["age"], not mymodule.person1["age"]
Python Datetime
❮ PreviousNext ❯

Python Dates
A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.

ExampleGet your own Python Server


Import the datetime module and display the current date:

import datetime

x = [Link]()
print(x)
Try it Yourself »

Date Output
When we execute the code from the example above the result will be:

2024-12-21 [Link].410896

The date contains year, month, day, hour, minute, second, and microsecond.

The datetime module has many methods to return information about the date
object.

Here are a few examples, you will learn more about them later in this chapter:

Example
Return the year and name of weekday:
import datetime

x = [Link]()

print([Link])
print([Link]("%A"))
Try it Yourself »

Creating Date Objects


To create a date, we can use the datetime() class (constructor) of
the datetime module.

The datetime() class requires three parameters to create a date: year, month,
day.

Example
Create a date object:

import datetime

x = [Link](2020, 5, 17)

print(x)
Try it Yourself »

The datetime() class also takes parameters for time and timezone (hour,
minute, second, microsecond, tzone), but they are optional, and has a default
value of 0, (None for timezone).

ADVERTISEMENT

The strftime() Method


The datetime object has a method for formatting date objects into readable
strings.
The method is called strftime(), and takes one parameter, format, to specify
the format of the returned string:

Example
Display the name of the month:

import datetime

x = [Link](2018, 6, 1)

print([Link]("%B"))
Try it Yourself »

A reference of all the legal format codes:

Directive Description Example

%a Weekday, short version Wed

%A Weekday, full version Wednesday

%w Weekday as a number 0-6, 0 is Sunday 3

%d Day of month 01-31 31

%b Month name, short version Dec

%B Month name, full version December


%m Month as a number 01-12 12

%y Year, short version, without century 18

%Y Year, full version 2018

%H Hour 00-23 17

%I Hour 00-12 05

%p AM/PM PM

%M Minute 00-59 41

%S Second 00-59 08

%f Microsecond 000000-999999 548513

%z UTC offset +0100

%Z Timezone CST
%j Day number of year 001-366 365

%U Week number of year, Sunday as the first day 52


of week, 00-53

%W Week number of year, Monday as the first day 52


of week, 00-53

%c Local version of date and time Mon Dec 31 [Link]


2018

%C Century 20

%x Local version of date 12/31/18

%X Local version of time [Link]

%% A % character %

%G ISO 8601 year 2018

%u ISO 8601 weekday (1-7) 1

%V ISO 8601 weeknumber (01-53) 01


Python Math
❮ PreviousNext ❯

Python has a set of built-in math functions, including an extensive math


module, that allows you to perform mathematical tasks on numbers.

Built-in Math Functions


The min() and max() functions can be used to find the lowest or highest value
in an iterable:

ExampleGet your own Python Server


x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)
Try it Yourself »

The abs() function returns the absolute (positive) value of the specified
number:

Example
x = abs(-7.25)

print(x)
Try it Yourself »

The pow(x, y) function returns the value of x to the power of y (x y).


Example
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

x = pow(4, 3)

print(x)
Try it Yourself »

ADVERTISEMENT

The Math Module


Python has also a built-in module called math, which extends the list of
mathematical functions.

To use it, you must import the math module:

import math

When you have imported the math module, you can start using methods and
constants of the module.

The [Link]() method for example, returns the square root of a number:

Example
import math

x = [Link](64)

print(x)
Try it Yourself »

The [Link]() method rounds a number upwards to its nearest integer, and
the [Link]() method rounds a number downwards to its nearest integer,
and returns the result:

Example
import math

x = [Link](1.4)
y = [Link](1.4)

print(x) # returns 2
print(y) # returns 1
Try it Yourself »

The [Link] constant, returns the value of PI (3.14...):

Example
import math

x = [Link]

print(x)
Try it Yourself »

Python JSON
❮ PreviousNext ❯

JSON is a syntax for storing and exchanging data.

JSON is text, written with JavaScript object notation.

JSON in Python
Python has a built-in package called json, which can be used to work with JSON
data.

ExampleGet your own Python Server


Import the json module:

import json
Parse JSON - Convert from JSON to
Python
If you have a JSON string, you can parse it by using the [Link]() method.

The result will be a Python dictionary.

Example
Convert from JSON to Python:

import json

# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = [Link](x)

# the result is a Python dictionary:


print(y["age"])

Try it Yourself »

Convert from Python to JSON


If you have a Python object, you can convert it into a JSON string by using
the [Link]() method.

Example
Convert from Python to JSON:

import json

# a Python object (dict):


x = {
"name": "John",
"age": 30,
"city": "New York"
}

# convert into JSON:


y = [Link](x)

# the result is a JSON string:


print(y)

Try it Yourself »

ADVERTISEMENT

You can convert Python objects of the following types, into JSON strings:

 dict
 list
 tuple
 string
 int
 float
 True
 False
 None

Example
Convert Python objects into JSON strings, and print the values:

import json

print([Link]({"name": "John", "age": 30}))


print([Link](["apple", "bananas"]))
print([Link](("apple", "bananas")))
print([Link]("hello"))
print([Link](42))
print([Link](31.76))
print([Link](True))
print([Link](False))
print([Link](None))

Try it Yourself »

When you convert from Python to JSON, Python objects are converted into the
JSON (JavaScript) equivalent:

Python JSON

dict Object

list Array

tuple Array

str String

int Number

float Number

True true

False false
None null

Example
Convert a Python object containing all the legal data types:

import json

x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}

print([Link](x))

Try it Yourself »

Format the Result


The example above prints a JSON string, but it is not very easy to read, with no
indentations and line breaks.
The [Link]() method has parameters to make it easier to read the result:

Example
Use the indent parameter to define the numbers of indents:

[Link](x, indent=4)

Try it Yourself »

You can also define the separators, default value is (", ", ": "), which means
using a comma and a space to separate each object, and a colon and a space to
separate keys from values:

Example
Use the separators parameter to change the default separator:

[Link](x, indent=4, separators=(". ", " = "))

Try it Yourself »

Order the Result


The [Link]() method has parameters to order the keys in the result:

Example
Use the sort_keys parameter to specify if the result should be sorted or not:

[Link](x, indent=4, sort_keys=True)

Try it Yourself »

Python RegEx
❮ PreviousNext ❯
A RegEx, or Regular Expression, is a sequence of characters that forms a
search pattern.

RegEx can be used to check if a string contains the specified search pattern.

RegEx Module
Python has a built-in package called re, which can be used to work with Regular
Expressions.

Import the re module:

import re

RegEx in Python
When you have imported the re module, you can start using regular
expressions:

ExampleGet your own Python Server


Search the string to see if it starts with "The" and ends with "Spain":

import re

txt = "The rain in Spain"


x = [Link]("^The.*Spain$", txt)

Try it Yourself »

RegEx Functions
The re module offers a set of functions that allows us to search a string for a
match:

Function Description

findall Returns a list containing all matches

search Returns a Match object if there is a match anywhere in the string

split Returns a list where the string has been split at each match

sub Replaces one or many matches with a string

Metacharacters
Metacharacters are characters with a special meaning:

Character Description Exampl

[] A set of characters "[a-m]"

\ Signals a special sequence (can also be used to escape special "\d"


characters)

. Any character (except newline character) "he..o"

^ Starts with "^hello"

$ Ends with "planet$

* Zero or more occurrences "he.*o"

+ One or more occurrences "he.+o"

? Zero or one occurrences "he.?o"

{} Exactly the specified number of occurrences "he.{2}o

| Either or "falls|sta

() Capture and group


Special Sequences
A special sequence is a \ followed by one of the characters in the list below, and
has a special meaning:

Character Description Exampl

\A Returns a match if the specified characters are at the beginning of "\AThe"


the string

\b Returns a match where the specified characters are at the r"\bain"


beginning or at the end of a word
(the "r" in the beginning is making sure that the string is being r"ain\b"
treated as a "raw string")

\B Returns a match where the specified characters are present, but r"\Bain"
NOT at the beginning (or at the end) of a word
(the "r" in the beginning is making sure that the string is being r"ain\B"
treated as a "raw string")

\d Returns a match where the string contains digits (numbers from "\d"
0-9)

\D Returns a match where the string DOES NOT contain digits "\D"

\s Returns a match where the string contains a white space "\s"


character
\S Returns a match where the string DOES NOT contain a white "\S"
space character

\w Returns a match where the string contains any word characters "\w"
(characters from a to Z, digits from 0-9, and the underscore _
character)

\W Returns a match where the string DOES NOT contain any word "\W"
characters

\Z Returns a match if the specified characters are at the end of the "Spain\Z
string

Sets
A set is a set of characters inside a pair of square brackets [] with a special
meaning:

Set Description

[arn] Returns a match where one of the specified characters ( a, r, or n) is present

[a-n] Returns a match for any lower case character, alphabetically between a and
[^arn] Returns a match for any character EXCEPT a, r, and n

[0123] Returns a match where any of the specified digits ( 0, 1, 2, or 3) are present

[0-9] Returns a match for any digit between 0 and 9

[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59

[a-zA-Z] Returns a match for any character alphabetically between a and z, lower cas
upper case

[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a m
for any + character in the string

The findall() Function


The findall() function returns a list containing all matches.

Example
Print a list of all matches:

import re

txt = "The rain in Spain"


x = [Link]("ai", txt)
print(x)

Try it Yourself »

The list contains the matches in the order they are found.

If no matches are found, an empty list is returned:

Example
Return an empty list if no match was found:

import re

txt = "The rain in Spain"


x = [Link]("Portugal", txt)
print(x)

Try it Yourself »

The search() Function


The search() function searches the string for a match, and returns a Match
object if there is a match.

If there is more than one match, only the first occurrence of the match will be
returned:

Example
Search for the first white-space character in the string:

import re

txt = "The rain in Spain"


x = [Link]("\s", txt)
print("The first white-space character is located in position:",
[Link]())

Try it Yourself »

If no matches are found, the value None is returned:

Example
Make a search that returns no match:

import re

txt = "The rain in Spain"


x = [Link]("Portugal", txt)
print(x)

Try it Yourself »

The split() Function


The split() function returns a list where the string has been split at each match:

Example
Split at each white-space character:

import re

txt = "The rain in Spain"


x = [Link]("\s", txt)
print(x)

Try it Yourself »

You can control the number of occurrences by specifying


the maxsplit parameter:
Example
Split the string only at the first occurrence:

import re

txt = "The rain in Spain"


x = [Link]("\s", txt, 1)
print(x)

Try it Yourself »

The sub() Function


The sub() function replaces the matches with the text of your choice:

Example
Replace every white-space character with the number 9:

import re

txt = "The rain in Spain"


x = [Link]("\s", "9", txt)
print(x)

Try it Yourself »

You can control the number of replacements by specifying the count parameter:

Example
Replace the first 2 occurrences:

import re

txt = "The rain in Spain"


x = [Link]("\s", "9", txt, 2)
print(x)

Try it Yourself »

Match Object
A Match Object is an object containing information about the search and the
result.

Note: If there is no match, the value None will be returned, instead of the Match
Object.

Example
Do a search that will return a Match Object:

import re

txt = "The rain in Spain"


x = [Link]("ai", txt)
print(x) #this will print an object

Try it Yourself »

The Match object has properties and methods used to retrieve information about
the search, and the result:

.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function
.group() returns the part of the string where there was a match

Example
Print the position (start- and end-position) of the first match occurrence.

The regular expression looks for any words that starts with an upper case "S":

import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link]())

Try it Yourself »

Example
Print the string passed into the function:

import re

txt = "The rain in Spain"


x = [Link](r"\bS\w+", txt)
print([Link])

Try it Yourself »

Example
Print the part of the string where there was a match.

The regular expression looks for any words that starts with an upper case "S":

import re

txt = "The rain in Spain"


x = [Link](r"\bS\w+", txt)
print([Link]())

Try it Yourself »

Note: If there is no match, the value None will be returned, instead of the Match
Object.

Python PIP
❮ PreviousNext ❯

What is PIP?
PIP is a package manager for Python packages, or modules if you like.

Note: If you have Python version 3.4 or later, PIP is included by default.

What is a Package?
A package contains all the files you need for a module.

Modules are Python code libraries you can include in your project.

Check if PIP is Installed


Navigate your command line to the location of Python's script directory, and
type the following:

ExampleGet your own Python Server


Check PIP version:

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\
Scripts>pip --version

Install PIP
If you do not have PIP installed, you can download and install it from this
page: [Link]

Download a Package
Downloading a package is very easy.
Open the command line interface and tell PIP to download the package you
want.

Navigate your command line to the location of Python's script directory, and
type the following:

Example
Download a package named "camelcase":

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\
Scripts>pip install camelcase

Now you have downloaded and installed your first package!

Using a Package
Once the package is installed, it is ready to use.

Import the "camelcase" package into your project.

Example
Import and use "camelcase":

import camelcase

c = [Link]()

txt = "hello world"

print([Link](txt))

Run Example »

Find Packages
Find more packages at [Link]

Remove a Package
Use the uninstall command to remove a package:

Example
Uninstall the package named "camelcase":

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\
Scripts>pip uninstall camelcase

The PIP Package Manager will ask you to confirm that you want to remove the
camelcase package:

Uninstalling camelcase-02.1:
Would remove:
c:\users\Your Name\appdata\local\programs\python\python36-32\
lib\site-packages\[Link]-info
c:\users\Your Name\appdata\local\programs\python\python36-32\
lib\site-packages\camelcase\*
Proceed (y/n)?

Press y and the package will be removed.

List Packages
Use the list command to list all the packages installed on your system:

Example
List installed packages:

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\
Scripts>pip list

Result:
Package Version
-----------------------
camelcase 0.2
mysql-connector 2.1.6
pip 18.1
pymongo 3.6.1
setuptools 39.0.1

Python Try Except


❮ PreviousNext ❯

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try-
and except blocks.

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

These exceptions can be handled using the try statement:

ExampleGet your own Python Server


The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")
Try it Yourself »

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example
This statement will raise an error, because x is not defined:

print(x)

Try it Yourself »

Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:

Example
Print one message if the try block raises a NameError and another for other
errors:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Try it Yourself »

Else
You can use the else keyword to define a block of code to be executed if no
errors were raised:

Example
In this example, the try block does not generate any error:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Try it Yourself »

Finally
The finally block, if specified, will be executed regardless if the try block raises
an error or not.

Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

Try it Yourself »

This can be useful to close objects and clean up resources:

Example
Try to open and write to a file that is not writable:

try:
f = open("[Link]")
try:
[Link]("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
[Link]()
except:
print("Something went wrong when opening the file")

Try it Yourself »

The program can continue, without leaving the file object open.

Raise an exception
As a Python developer you can choose to throw an exception if a condition
occurs.

To throw (or raise) an exception, use the raise keyword.

Example
Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

Try it Yourself »

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example
Raise a TypeError if x is not an integer:

x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")

Python User Input


❮ PreviousNext ❯

User Input
Python allows for user input.

That means we are able to ask the user for input.

The method is a bit different in Python 3.6 than Python 2.7.

Python 3.6 uses the input() method.

Python 2.7 uses the raw_input() method.

The following example asks for the username, and when you entered the
username, it gets printed on the screen:

Python 3.6Get your own Python Server


username = input("Enter username:")
print("Username is: " + username)

Run Example »

Python 2.7
username = raw_input("Enter username:")
print("Username is: " + username)

Run Example »

Python stops executing when it comes to the input() function, and continues
when the user has given some input.
Python String Formatting
❮ PreviousNext ❯

F-String was introduced in Python 3.6, and is now the preferred way of
formatting strings.

Before Python 3.6 we had to use the format() method.

F-Strings
F-string allows you to format selected parts of a string.

To specify a string as an f-string, simply put an f in front of the string literal, like
this:

ExampleGet your own Python Server


Create an f-string:

txt = f"The price is 49 dollars"


print(txt)

Try it Yourself »

Placeholders and Modifiers


To format values in an f-string, add placeholders {}, a placeholder can contain
variables, operations, functions, and modifiers to format the value.

Example
Add a placeholder for the price variable:
price = 59
txt = f"The price is {price} dollars"
print(txt)

Try it Yourself »

A placeholder can also include a modifier to format the value.

A modifier is included by adding a colon : followed by a legal formatting type,


like .2f which means fixed point number with 2 decimals:

Example
Display the price with 2 decimals:

price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)

Try it Yourself »

You can also format a value directly without keeping it in a variable:

Example
Display the value 95 with 2 decimals:

txt = f"The price is {95:.2f} dollars"


print(txt)

Try it Yourself »

Perform Operations in F-Strings


You can perform Python operations inside the placeholders.

You can do math operations:

Example
Perform a math operation in the placeholder, and return the result:

txt = f"The price is {20 * 59} dollars"


print(txt)

Try it Yourself »

You can perform math operations on variables:

Example
Add taxes before displaying the price:

price = 59
tax = 0.25
txt = f"The price is {price + (price * tax)} dollars"
print(txt)

Try it Yourself »

You can perform if...else statements inside the placeholders:

Example
Return "Expensive" if the price is over 50, otherwise return "Cheap":

price = 49
txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"

print(txt)

Try it Yourself »

Execute Functions in F-Strings


You can execute functions inside the placeholder:

Example
Use the string method upper()to convert a value into upper case letters:
fruit = "apples"
txt = f"I love {[Link]()}"
print(txt)

Try it Yourself »

The function does not have to be a built-in Python method, you can create your
own functions and use them:

Example
Create a function that converts feet into meters:

def myconverter(x):
return x * 0.3048

txt = f"The plane is flying at a {myconverter(30000)} meter


altitude"
print(txt)

Try it Yourself »

More Modifiers
At the beginning of this chapter we explained how to use the .2f modifier to
format a number into a fixed point number with 2 decimals.

There are several other modifiers that can be used to format values:

Example
Use a comma as a thousand separator:

price = 59000
txt = f"The price is {price:,} dollars"
print(txt)

Try it Yourself »

Here is a list of all the formatting types.


Formatting Types

: Try Left aligns the result (within the available space)


< it

: Try Right aligns the result (within the available space)


> it

: Try Center aligns the result (within the available space)


^ it

: Try Places the sign to the left most position


= it

: Try Use a plus sign to indicate if the result is positive or negative


+ it

: Try Use a minus sign for negative values only


- it

: Try Use a space to insert an extra space before positive numbers (and a minus sign b
it negative numbers)
: Try Use a comma as a thousand separator
, it

: Try Use a underscore as a thousand separator


_ it

: Try Binary format


b it

: Converts the value into the corresponding Unicode character


c

: Try Decimal format


d it

: Try Scientific format, with a lower case e


e it

: Try Scientific format, with an upper case E


E it

: Try Fix point number format


f it

: Try Fix point number format, in uppercase format (show inf and nan as INF and NAN
it
F

: General format
g

: General format (using a upper case E for scientific notations)


G

: Try Octal format


o it

: Try Hex format, lower case


x it

: Try Hex format, upper case


X it

: Number format
n

: Try Percentage format


% it
String format()
Before Python 3.6 we used the format() method to format strings.

The format() method can still be used, but f-strings are faster and the preferred
way to format strings.

The next examples in this page demonstrates how to format strings with
the format() method.

The format() method also uses curly brackets as placeholders {}, but the syntax
is slightly different:

Example
Add a placeholder where you want to display the price:

price = 49
txt = "The price is {} dollars"
print([Link](price))

Try it Yourself »

You can add parameters inside the curly brackets to specify how to convert the
value:

Example
Format the price to be displayed as a number with two decimals:

txt = "The price is {:.2f} dollars"

Try it Yourself »

Check out all formatting types in our String format() Reference.

Multiple Values
If you want to use more values, just add more values to the format() method:
print([Link](price, itemno, count))

And add more placeholders:

Example
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print([Link](quantity, itemno, price))

Try it Yourself »

Index Numbers
You can use index numbers (a number inside the curly brackets {0}) to be sure
the values are placed in the correct placeholders:

Example
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f}
dollars."
print([Link](quantity, itemno, price))

Try it Yourself »

Also, if you want to refer to the same value more than once, use the index
number:

Example
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print([Link](age, name))

Try it Yourself »
Named Indexes
You can also use named indexes by entering a name inside the curly
brackets {carname}, but then you must use names when you pass the parameter
values [Link](carname = "Ford"):

Example
myorder = "I have a {carname}, it is a {model}."
print([Link](carname = "Ford", model = "Mustang"))

Try it Yourself »

You might also like