Basic types

In this section we go through the built-in basic types offered by Python: int, float, bool, NoneType and str.

Integers

The most basic numerical type is the integer. Python considers any number without a decimal point to be of type int:

>>> n = 6
>>> type(n)
<class 'int'>

Integers support the usual arithmetic operations + (sum), - (substraction), * (product), // (integer division), % (remainder of division), ** (power) and they can be compared with relational operators (==, !=, <, <=, >, >=):

>>> 22 // 7
3
>>> 22 / 7          # By default, division casts to floating-point type
3.142857142857143

One remarkable feature is that integers are of variable precision and there is no need to worry about overflow issues:

>>> 2 ** 100
1267650600228229401496703205376

Floating-point numbers

The float type represents real numbers and they can be defined either in standard decimal notation or in exponential notation:

>>> n = 1.23
>>> G = 6.67408e-11

They support the same arithmetic and relational operators as integers, exchanging the integer division // by the real division /.

Boolean

The boolean type has two possible values: True and False. Relational operators such as ==, !=, <, <=, >, >= return booleans and they can be operated by means of and (conjunction), or (disjunction) and not (negation).

None Type

Python offers one special value None of type NoneType that is frequently used to represent the absence of a value.

Conversions

In Python you can explicitly convert different types using the desired name of the type as if it were a function. For instance, to convert into integers:

>>> int(6.66)
6
>>> int(9.99)
9
>>> int('23')
23
>>> int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve'

Or to convert into floats:

>>> float(12)
12.0
>>> float('12')
12.0
>>> float('12.24')
12.24

Most values can be converted into strings using the str() function:

>>> str(33)
'33'
>>> str(3.1416)
'3.1416'
>>> str(False)
'False'
>>> str([1, 'one', []])
"[1, 'one', []]"

Strings

Strings in Python are of type str and consist in sequences of Unicode characters (an standard for the representation of text). Values in strings are immutable: they cannot be modified once they are created. All you can do is create new strings from them.

Note that the character type does not exist in Python.

Representation

Strings are created with single or double quotes:

You can also have multiline strings using three quotation marks:

html = """
    <html>
        <head>
            <title>My title</</title>
        </head>
        <body>
            <h1>Introduction</h1>
            <p>
                Some text
            </p>
        </body>
    </html>
"""

Functions for length, minimum and maximum

The len() function returns the number of characters in a string:

>>> len('Everest')
7
>>> len('A')
1

The min() and max() functions return the smallest and largest character in a string respectively.

>>> min('Everest')
'E'
>>> max('Everest')
'v'

Operators

These are some of the operators that can be applied to strings:

For instance:

>>> 'Julius' + ' ' + 'Caesar'
'Julius Caesar'
>>> 'spam' * 5
'spamspamspamspamspam'
>>> 'flame' in 'the flame that burns twice as bright burns half as long'
True
>>> 'c' < 'python'
True

Iterating

In order to iterate all the characters in a string, a for loop is used:

def number_of_as(text):
    n = 0
    for c in text:
        if c == "A":
            n += 1
    return n

More insight on for loops is given in the Control flow section.

Substrings

You can create a substring using the indexing operator [], starting from 0:

>>> 'snowing'[0]
's'
>>> 'snowing'[3]
'w'
>>> 'snowing'[7]
IndexError: string index out of range

Elements at the end can be accessed using a negative index, starting from -1:

>>> 'snowing'[-1]
'g'
>>> 'snowing'[-7]
'2'
>>> 'snowing'[-8]
IndexError: string index out of range

In order to extract the substring between two positions you can use the syntax s[start:stop]. Note that stopping point is never part of the generated substring:

>>> 'snowing'[0:4]
'snow'
>>> 'snowing'[1:4]
'now'
>>> 'snowing'[3:4]
'w'
>>> 'snowing'[4:4]
''

In case start is not given it means “from the beginning”. Similarly, if stop is not given it means “until the end”:

>>> 'snowing'[:4]
'snow'
>>> 'snowing'[4:]
'ing'

You can also specify a step by means of s[start:stop:step]:

>>> 'snowing'[0:5:2]
'soi'
>>> 'snowing'[::2]  # Equivalent to l[0:len(l):2]
'soig'
>>> 'snowing'[::-1]
'gniwons'

As we highlighted before, strings are immutable and their characters cannot be modified:

>>> s = 'snowing'
>>> s[0] = 'k'
TypeError: 'str' object does not support item assignment

In order to obtain 'knowing' you can do something like

>>> s = 'k' + s[1:]
>>> s
'knowing'

Methods

Strings are objects with many available methods. Here are a few of them:

For a complete outlook of all the available methods refer to the Python documentation or type

>>> help(str)

Substitutions and format

The format() method enables replacements and variable formatting inside a string. Check the documentation about formatting in Python for much more information details (including the new fstrings in Python ≥3.6).

This simple example shows how to apply substitutions in a string:

>>> '{} is {}m high'.format('Mount Everest', 8848)
'Mount Everest is 8848m high'

In case you want to format a floating point number you can specify additional options:

>>> "{}".format(3.65)
'3.65'
>>> "{:.10f}".format(3.65)      # Adds 10 digits after the decimal point
'3.6500000000'
"{:7.3f}".format(3.65)          # Uses 7 characters, 3 of which are after the decimal point
'  3.650'




Lliçons.jutge.org
Víctor Adell
Universitat Politècnica de Catalunya, 2023

Prohibit copiar. Tots els drets reservats.
No copy allowed. All rights reserved.