Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Python Strings

Eng. Emanuel Rashayi


Faculty of Engineering, Dept of Electrical & Electronics Engineering , University of Zimbabwe
erashayi@eng.uz.ac.zw
Python 3 Strings – Introduction

❑ A string is a sequence of characters, meaning: letters, numbers


and other characters like the dollar sign, spaces and punctuation
marks enclosed by single quotes, double quotes or even triple
quotes when spanning multiple lines.
Python 3 Strings – Introduction
Python 3 Strings – Introduction
Python 3 Strings – Indexing

• Python uses indexes to mark the position of an element within a sequence of


elements; a string is a sequence of elements and the elements of a string are the
characters themselves. One character, one element.
• The first element of any sequence, when counting from left to right, has the index 0
Python 3 Strings – Indexing
Python 3 Strings – Indexing
Python 3 Strings – Methods
Python 3 Strings – Methods
Python 3 Strings – Methods

a comprehensive list of string methods :


https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
Python 3 Strings - Operators & Formatting
Python 3 Strings - Formatting

Lets look at this string: "Cisco model: 2600XM, 2 WAN slots, IOS 12.4“
We may use this as a template and ONLY change those in red when there is need
The syntax will be as follows:
"Cisco model: %s, %d WAN slots, IOS %f" % ("2600XM", 2, 12.4)”
Python 3 Strings - Formatting

Lets look at this string: "Cisco model: 2600XM, 2 WAN slots, IOS 12.4“

We can also use the .format() method


"Cisco model: {}, {} WAN slots, IOS {}".format("2600XM", 2, 12.4)

We can also use some sort of indexing when dealing with this type of string
formatting.
"Cisco model: {0}, {1} WAN slots, IOS {2}".format("2600XM", 2, 12.4)
Python 3 Strings - Formatting
Python 3 Strings – Slices

Slices allow us to extract various parts of a string (or list, or other sequence of elements),
leaving the initial string unchanged.
The syntax for a string slice is the following:
mystring[10: 15
The slice will go up to, but will not include, the index specified on the right side of the
colon
Python 3 Strings – Slices
Python 3 Numbers - Math Operators

The first thing I should mention here is that Python defines three numerical types.
They are: integers, floating-point numbers and complex numbers.
Python 3 Numbers - Math Operators

You might also like