Strings#

Text is a string data type. Any data type written as text is a string. Any data under single, double or triple quote are strings. There are different string methods and built-in functions to deal with string data types. To check the length of a string use the len() method.

Creating a string#

letter = "P"  # A string could be a single character or a bunch of texts
print(letter)  # P
print(len(letter))  # 1
greeting = "Hello, World!"  # String could be made using a single or double quote,"Hello, World!"
print(greeting)  # Hello, World!
print(len(greeting))  # 13
sentence = "I hope you are enjoying Applied Python Training"
print(sentence)
P
1
Hello, World!
13
I hope you are enjoying Applied Python Training

Multiline string is created by using triple single (‘’’) or triple double quotes (“””). See the example below.

multiline_string = """I am an engineer and enjoy sharing.
I didn't find anything as rewarding as empowering people.
That is why I created Applied Python Training."""
print(multiline_string)
I am an engineer and enjoy sharing.
I didn't find anything as rewarding as empowering people.
That is why I created Applied Python Training.

String Concatenation#

We can connect strings together. Merging or connecting strings is called concatenation. See the example below:

first_name = "Aurora"
last_name = "Luna"
space = " "
full_name = first_name + space + last_name
print(full_name)
# Checking the length of a string using len() built-in function
print(len(first_name))
print(len(last_name))
print(len(first_name) > len(last_name))  # True
print(len(full_name))
Aurora Luna
6
4
True
11

Escape Sequences in Strings#

In Python and other programming languages \ followed by a character is an escape sequence. Let us see the most common escape characters:

  • \n: new line

  • \t: Tab means(8 spaces)

  • \\: Back slash

  • \': Single quote (‘)

  • \": Double quote (“)

Now, let us see the use of the above escape sequences with examples.

print("I hope everyone is enjoying the Python Training.\nAre you ?")  # line break
print("Days\tTopics\tExercises")  # adding tab space or 4 spaces
print("Day 1\t5\t5")
print("Day 2\t6\t20")
print("Day 3\t5\t23")
print("Day 4\t1\t35")
print("This is a backslash  symbol (\\)")  # To write a backslash
print(
    'In every programming language it starts with "Hello, World!"'
)  # to write a double quote inside a single quote
I hope everyone is enjoying the Python Training.
Are you ?
Days	Topics	Exercises
Day 1	5	5
Day 2	6	20
Day 3	5	23
Day 4	1	35
This is a backslash  symbol (\)
In every programming language it starts with "Hello, World!"

String formatting#

Old Style String Formatting (% Operator)#

In Python there are many ways of formatting strings. In this section, we will cover some of them. The “%” operator is used to format a set of variables enclosed in a “tuple” (a fixed size list), together with a format string, which contains normal text together with “argument specifiers”, special symbols like “%s”, “%d”, “%f”, “%.nf”.

  • %s - String (or any object with a string representation, like numbers)

  • %d - Integers

  • %f - Floating point numbers

  • "%.nf" - Floating point numbers with fixed n precision

# Strings only
first_name = "Aurora"
last_name = "Luna"
language = "Python"
formated_string = "I am %s %s. I learn %s" % (first_name, last_name, language)
print(formated_string)

# Strings  and numbers
radius = 10
pi = 3.14
area = pi * radius**2
formated_string = "The area of circle with a radius %d is %.2f." % (
    radius,
    area,
)  # 2 refers the 2 significant digits after the point

python_libraries = ["Django", "Flask", "NumPy", "Matplotlib", "Pandas"]
formated_string = "The following are python libraries:%s" % (python_libraries)
print(
    formated_string
)  # "The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']"
I am Aurora Luna. I learn Python
The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib', 'Pandas']

New Style String Formatting (str.format)#

This formatting is introduced in Python version 3.

first_name = "Aurora"
last_name = "Luna"
language = "Python"
formated_string = "I am {} {}. I learn {}".format(first_name, last_name, language)
print(formated_string)
a = 4
b = 3

print("{} + {} = {}".format(a, b, a + b))
print("{} - {} = {}".format(a, b, a - b))
print("{} * {} = {}".format(a, b, a * b))
print("{} / {} = {:.2f}".format(a, b, a / b))  # limits it to two digits after decimal
print("{} % {} = {}".format(a, b, a % b))
print("{} // {} = {}".format(a, b, a // b))
print("{} ** {} = {}".format(a, b, a**b))

# Strings  and numbers
radius = 10
pi = 3.14
area = pi * radius**2
formated_string = "The area of a circle with a radius {} is {:.2f}.".format(
    radius, area
)  # 2 digits after decimal
print(formated_string)
I am Aurora Luna. I learn Python
4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1.33
4 % 3 = 1
4 // 3 = 1
4 ** 3 = 64
The area of a circle with a radius 10 is 314.00.

String Interpolation / f-Strings (Python 3.6+)#

Another new string formatting is string interpolation, f-strings. Strings start with f and we can inject the data in their corresponding positions.

a = 4
b = 3
print(f"{a} + {b} = {a +b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b:.2f}")
print(f"{a} % {b} = {a % b}")
print(f"{a} // {b} = {a // b}")
print(f"{a} ** {b} = {a ** b}")
4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1.33
4 % 3 = 1
4 // 3 = 1
4 ** 3 = 64

Python Strings as Sequences of Characters#

Python strings are sequences of characters, and share their basic methods of access with other Python ordered sequences of objects – lists and tuples. The simplest way of extracting single characters from strings (and individual members from any sequence) is to unpack them into corresponding variables.

Unpacking Characters#

language = "Python"
a, b, c, d, e, f = language  # unpacking sequence characters into variables
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
P
y
t
h
o
n

Accessing Characters in Strings by Index#

In Python, indexing starts from zero. Therefore the first letter of a string is at zero index and the last letter of a string is the length of a string minus one.

P

y

t

h

o

n

0

1

2

3

4

5

language = "Python"
first_letter = language[0]
print(first_letter)
second_letter = language[1]
print(second_letter)
last_index = len(language) - 1
last_letter = language[last_index]
print(last_letter)
P
y
n

If we want to start from right end we can use negative indexing. -1 is the last index.

language = "Python"
last_letter = language[-1]
print(last_letter)
second_last = language[-2]
print(second_last)
n
o

Slicing Python Strings#

In python we can slice strings into substrings.

language = "Python"
first_three = language[0:3]  # starts at zero index and up to 3 but not include 3
print(first_three)
last_three = language[3:6]
print(last_three)
# Another way
last_three = language[-3:]
print(last_three)
last_three = language[3:]
print(last_three)
Pyt
hon
hon
hon

Reversing a String#

We can easily reverse strings in python.

greeting = "Hello, World!"
print(greeting[::-1])
!dlroW ,olleH

Skipping Characters While Slicing#

It is possible to skip characters while slicing by passing step argument to slice method.

language = "Python"
pto = language[0:6:2]
print(pto)
Pto

String Methods#

There are many string methods which allow us to format strings. You can refer to all of them from here: https://docs.python.org/3/library/stdtypes.html#string-methods