Classes Till String Formating
Classes Till String Formating
❮ PreviousNext ❯
Python Classes/Objects
Python is an object oriented programming language.
Create a Class
To create a class, use the keyword class:
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 »
All classes have a function called __init__(), which is always executed when
the class is being initiated.
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.
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.
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 »
Example
Set the age of p1 to 40:
[Link] = 40
Try it Yourself »
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 »
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.
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 »
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
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.
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.
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
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:
print(next(myit))
print(next(myit))
print(next(myit))
Try it Yourself »
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:
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 »
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.
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 ❯
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 ❯
def myfunc():
x = 300
print(x)
myfunc()
Try it Yourself »
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.
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
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 »
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.
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:
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.
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 »
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
Example
Display the name of the month:
import datetime
x = [Link](2018, 6, 1)
print([Link]("%B"))
Try it Yourself »
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%Z Timezone CST
%j Day number of year 001-366 365
%C Century 20
%% A % character %
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 »
x = pow(4, 3)
print(x)
Try it Yourself »
ADVERTISEMENT
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 »
Example
import math
x = [Link]
print(x)
Try it Yourself »
Python JSON
❮ PreviousNext ❯
JSON in Python
Python has a built-in package called json, which can be used to work with JSON
data.
import json
Parse JSON - Convert from JSON to
Python
If you have a JSON string, you can parse it by using the [Link]() method.
Example
Convert from JSON to Python:
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = [Link](x)
Try it Yourself »
Example
Convert from Python to JSON:
import json
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
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 »
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:
Try it Yourself »
Example
Use the sort_keys parameter to specify if the result should be sorted or not:
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 re
RegEx in Python
When you have imported the re module, you can start using regular
expressions:
import re
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
split Returns a list where the string has been split at each match
Metacharacters
Metacharacters are characters with a special meaning:
| Either or "falls|sta
\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"
\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
[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
[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
Example
Print a list of all matches:
import re
Try it Yourself »
The list contains the matches in the order they are found.
Example
Return an empty list if no match was found:
import re
Try it Yourself »
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
Try it Yourself »
Example
Make a search that returns no match:
import re
Try it Yourself »
Example
Split at each white-space character:
import re
Try it Yourself »
import re
Try it Yourself »
Example
Replace every white-space character with the number 9:
import re
Try it Yourself »
You can control the number of replacements by specifying the count parameter:
Example
Replace the first 2 occurrences:
import re
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
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
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
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.
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
Using a Package
Once the package is installed, it is ready to use.
Example
Import and use "camelcase":
import camelcase
c = [Link]()
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)?
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
The try block lets you test a block of code for errors.
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.
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 »
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.
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 »
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")
User Input
Python allows for user input.
The following example asks for the username, and when you entered the
username, it gets printed on the screen:
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.
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:
Try it Yourself »
Example
Add a placeholder for the price variable:
price = 59
txt = f"The price is {price} dollars"
print(txt)
Try it Yourself »
Example
Display the price with 2 decimals:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Try it Yourself »
Example
Display the value 95 with 2 decimals:
Try it Yourself »
Example
Perform a math operation in the placeholder, and return the result:
Try it Yourself »
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 »
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 »
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
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 »
: 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 Fix point number format, in uppercase format (show inf and nan as INF and NAN
it
F
: General format
g
: Number format
n
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:
Try it Yourself »
Multiple Values
If you want to use more values, just add more values to the format() method:
print([Link](price, itemno, count))
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 »