0% found this document useful (0 votes)
2 views102 pages

Strings in Python

The document outlines a training program aimed at bridging the digital skills gap for over 10 million young professionals, focusing on careers in future technology. It includes an introduction to strings in Python, covering topics such as string creation, indexing, operations, and slicing. The document provides examples and explanations of string manipulation techniques in Python.

Uploaded by

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

Strings in Python

The document outlines a training program aimed at bridging the digital skills gap for over 10 million young professionals, focusing on careers in future technology. It includes an introduction to strings in Python, covering topics such as string creation, indexing, operations, and slicing. The document provides examples and explanations of string manipulation techniques in Python.

Uploaded by

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

We are on a mission to address the digital

skills gap for 10 Million+ young professionals,


train and empower them to forge a career
path into future tech
Strings in Python
MONTH, YEAR
Strings in Python - Outline
▪ Introduction to Strings

▪ String Operations

▪ Traversing a String

▪ String Built-in functions

▪ String Formatting in Python

3 Strings in Python | © SmartCliff | Internal | Version 1.0


INTRODUCTION
TO
STRINGS

4 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

What is Strings?

✓ Strings in Python can be a combination of characters like alphabets and /or digits and /or special
symbols. In other words, a String is a sequence that is made up of one or more UNICODE
characters.

Notes

Unicode is a popular encoding standard. It is an international character encoding standard that


provides a unique number for every character across languages making almost all characters
accessible across platforms, programs, and devices.

5 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

What is Strings?

✓ A string can be created by enclosing one or more characters in single, double, or triple quotes.

Single Line String (Single Quotes / Double Quotes)

✓ Python treats single quotes the same as double quotes.

Example #1: String can be represented using single, double


str1 = ‘ Hello World! '
str2 = “ Hello World! "
✓ Creating strings is as simple as assigning a value to a variable. All white space i.e. spaces and tabs
are preserved as-is:
my_string = “This is an example sentence with spaces and tabs”
print(my_string)
This is an example sentence with spaces and tabs #Output

6 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

What is Strings?

Multi-line String (Triple Quotes)

✓ You can specify multi-line strings using triple quotes (””” or ''').

Example#2:
str3 = “ “ “ Hello World! “ “ “
str4 = ‘ ‘ ‘ Hello World! ‘ ‘ ‘

✓ You can use single quotes and double quotes freely within the triple quotes.

Example#3:
‘ ‘ ‘ This is a multi-line string. This is the first line.
This is the second line.
“ What's your name?,” I asked.
He said "Bond, James Bond ’ ’ ’

7 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

What is Strings?

Example #4: Values stored in str3 can be extended to multiple lines using triple codes .

# Multiple lines using triple quotes

str3 = ‘Hello World!’

str3 = “ “ “ Hello World!

welcome to the world of Python” ” ”

8 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

Accessing the characters in a String

✓ Each individual character in a string can be accessed using a technique called indexing.

✓ Each item in a string corresponds to an index number, which is an integer value, starting with the

index number 0.

✓ The below example shows that the variable “Greetings” has initialized with the string “HELLO” and the

index breakdown looks like this :

Greetings = H E L L O
0 1 2 3 4

9 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

Accessing the characters in a String

✓ Python supports two types of indexing namely: Positive Index and Negative Index.

✓ Positive Index: This index is used when we want to access the characters of the string from left
to right. This index starts from 0 and increments 1 to all other characters of the string.

✓ Negative index: This index is used when we want to access the characters of the string from right
to left. Start with the index as -1 and the last character has the index –n where n is the length of
the string.

✓ For Example: str1=“HELLO WORLD!” Negative Index

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

H E L L O W O R L D !
str1 =
0 2 3 4 5 6 7 8 9 10 11

Positive Index
10 Strings in Python | © SmartCliff | Internal | Version 1.0
Introduction to Strings

Accessing the characters in a String

✓ The index specifies the character to be accessed in the String and is written in square brackets ([ ]).

Example #5: Accessing the characters of the string using Index

#initializes a String str1


str1 = 'Hello World!' str1 H e l l 0 W o r l d !

#gives the first character of str1 positive


0 1 2 3 4 5 6 7 8 9 10 11
index
print(str1[0])
'H'
#gives seventh character of str1 str1 H e l l 0 W o r l d !

print(str1[6]) positive
0 1 2 3 4 5 6 7 8 9 10 11
index
'W'
11 Strings in Python | © SmartCliff | Internal | Version 1.0
Introduction to Strings

Accessing the characters in a String

✓In case, if we give an index value out of this range then the interpreter will raise IndexError.

Example #5: Index Out of range

#gives an error as index is out of range


str1 H e l l 0 W o r l d !

print(str1[15]) positive
0 1 2 3 4 5 6 7 8 9 10 11
index

IndexError : String index out of range

12 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

Accessing the characters in a String

✓ The index can also be an expression including variables and operators but the expression must
evaluate to an integer.

Example #6: Expression in index

# an expression resulting in an integer index str1 H e l l 0 W o r l d !

# so gives 6th character of str1


positive
0 1 2 3 4 5 6 7 8 9 10 11
index
print(str1[2+4])
‘W’
#gives an error as the index must be an integer
print(str1[1.5])
TypeError: String indices must be integers

13 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

Accessing the characters in a String

✓ Example #7: Accessing the string using Negative Index

#gives the first character from the right Negative


-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Index
print(str1[-1])
str1 H e l l 0 W o r l d !
‘!’ positive
0 1 2 3 4 5 6 7 8 9 10 11
index

#gives the last character from the right Negative


-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Index
print(str1[-12])
str1 H e l l 0 W o r l d !
‘H’ positive
0 1 2 3 4 5 6 7 8 9 10 11
index

14 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

Find Length

✓ An inbuilt function len() in Python returns the length of the String that is passed as a parameter.

Example #8:Finding the length of the string

# gives the length of the String str1


str1 = 'Hello World!’ Negative
Index
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

print(len(str1)) str1 H e l l 0 W o r l d !

positive
0 1 2 3 4 5 6 7 8 9 10 11
12 index

# length of the String is assigned to n


n = len(str1)
print(n)
12

15 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

Find Length

# gives the last character of the String


str1 H e l l 0 W o r l d !

print(str1[n-1]) positive
0 1 2 3 4 5 6 7 8 9 10 11
index
'!’
# gives the first character of the string
Negative
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Index
print(str1[-n] )
str1 H e l l 0 W o r l d !
'H'

16 Strings in Python | © SmartCliff | Internal | Version 1.0


Introduction to Strings

String is Immutable

✓ A string is an immutable data type. It means that the contents of the string cannot be changed(add,

modify, delete) after it has been created.

✓ If we try to change the string will raise the error called Type error.

Example #9: Trying to change the character of a string using Index.

print(str1 = "Hello World!“)


Negative
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
#if we try to replace character 'e' with 'a’ Index

str1 H e l l 0 W o r l d !
str1[1] = ‘a’ positive
0 1 2 3 4 5 6 7 8 9 10 11
index
print(str1)
TypeError: 'str' object does not support item assignment

17 Strings in Python | © SmartCliff | Internal | Version 1.0


STRING
OPERATIONS

18 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

Types of String Operations

✓ As we know that string is a sequence of characters. Python allows certain operations on string

data types, as below:

String Operations

Concatenations Repetitions Membership Slicing

19 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

String Concatenation

✓ Python allows to join or concatenate the two strings using the concatenation operator “plus”
which is denoted by the symbol ‘+’.

✓ Example #1:Concatenate the two strings

str1 = 'Hello’ #First String


str2 = 'World!’ #Second String
print(str1 + str2) #Concatenated Strings
'HelloWorld!’
print(str1)
'Hello’ # str1 and str2 remain the same after this operation.
print(str2)
'World!'
20 Strings in Python | © SmartCliff | Internal | Version 1.0
String Operations

String Repetition

✓ The repetition is use to iterate a string “n” number of times in Python.

✓ The “*” operator takes a desired string that needs to be repeated to a particular integer number
and generates a new string.

✓ Example #2: returns the multiple copies of a String and joins them all together.

#assign String 'Hello' to str1


str1 = 'Hello'
#repeat the value of str1 2 times
print(str1 * 2)
'HelloHello'

21 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

Membership

✓ Python has two membership operators 'in' and 'not in’.

✓ The 'in' operator takes two Strings and returns True if the first String appears as a substring in the
second string, otherwise it returns False.

Example #3: Checking the availability of the substring in string

str1 = 'Hello World!’


print('W' in str1)
True
print(Wor' in str1)
True
print('My' in str1)
False

22 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

Membership

✓ The not in operator returns True if the element is not present in the String, else it returns False.

Example #4: Checking the availability of the substring in string

str1 = 'Hello World!’


print(‘My' not in str1)
True
print('Hello' not in str1)
False

23 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

String Slicing

✓ In Python, to access some part of a string or substring, we use a method called slicing.

✓ This can be done by specifying an index range.

✓ Given a string str1, the slice operation str1[n:m] returns the part of the string str1 starting from

index n (inclusive) and ending at m (exclusive).

✓ In other words, we can say that str1[n:m] returns all the characters starting from str1[n] till str1[m-1].

✓ The numbers of characters in the substring will always be equal to difference of two indices m and

n, that is (m-n)

24 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

String Slicing

Example #5:Slicing the string using index

str1 = 'Hello World!'


str1 H e l l 0 W o r l d !
#gives subString starting from index 1 to 4
positive
0 1 2 3 4 5 6 7 8 9 10 11
print(str1[1:5]) index

'ello’
str1 H e l l 0 W o r l d !
#gives substring starting from 7 to 9
positive
print(str1[7:10] ) index
0 1 2 3 4 5 6 7 8 9 10 11

'orl'

25 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

String Slicing

#index that is too big is truncated down to the end of the String
str1 H e l l 0 W o r l d !
print(str1[3:20])
positive
0 1 2 3 4 5 6 7 8 9 10 11
index
'lo World!’

#first index > second index results in an empty ‘ ’ string

print(str1[7:2])

26 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

String Slicing

Example #6: If the first index is not mentioned, the slice starts from index.

str1 = 'Hello World!’


str1 H e l l 0 W o r l d !
#gives subString from index 0 to 4
positive
print(str1[:5]) 0 1 2 3 4 5 6 7 8 9 10 11
index

'Hello'

Example #7: If the second index is not mentioned, the slicing is done till the length of the String.

#gives subString from index 6 to end str1 H e l l 0 W o r l d !

print(str1[6:]) positive
0 1 2 3 4 5 6 7 8 9 10 11
index
'World!'

27 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

String Slicing

Example #8: Negative indexes can also be used for slicing.

#characters at index -6,-5,-4,-3 and -2 are Negative


-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Index
#sliced
str1 H e l l 0 W o r l d !

print(str1[-6:-1]) positive
0 1 2 3 4 5 6 7 8 9 10 11
index
'World'

28 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

String Slicing

✓The slice operation can also take a third index that specifies the ‘step size’.

✓ For example, str1[n:m:k], means every kth character has to be extracted from the String str1 starting
from n and ending at m-1. By default, the step size is one.

Example #9: Slicing the string with a step size.

print(str1[0:10:2]) str1 H e l l 0 W o r l d !

'HloWr’ positive
0 1 2 3 4 5 6 7 8 9 10 11
index

print(str1[0:10:3]) str1 H e l l 0 W o r l d !

‘HlWl’ positive
0 1 2 3 4 5 6 7 8 9 10 11
index

29 Strings in Python | © SmartCliff | Internal | Version 1.0


String Operations

String Slicing

Example #9: If we ignore both the indexes and give step size as -1.

#By default, the step size is 1 but that extra colon before the numbers allows us to specify the
str1 H e l l 0 W o r l d !
slicing increment.
positive
0 1 2 3 4 5 6 7 8 9 10 11
print(str1[::2]) index

Hlowrd
str1 H e l l 0 W o r l d !
print(str1[::3]) positive
0 1 2 3 4 5 6 7 8 9 10 11
index
HlWl
Negative
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
#str1 String is obtained in the reverse order Index

str1 H e l l 0 W o r l d !
print(str1[::-1])
positive
0 1 2 3 4 5 6 7 8 9 10 11
'!dlroW olleH' index

30 Strings in Python | © SmartCliff | Internal | Version 1.0


TRAVERSING A
STRING

31 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

What is traversal?

✓ Processing a String one item at a time. Often, they start at the beginning, select each item in turn,

process and continue until the end. This pattern of processing is called a traversal.

✓ We can access each element of the String or traverse a String using a for loop or a while loop.

Syntax :
for variable in sequence: while condition :

statement indented Block

for loop while loop

32 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

String traversal using for loop : Example #1

✓ A String is a sequence of items, so the for loop iterates over each item in the String automatically.

Program
# Example: Iterating the sequence of elements using for loop.
1. str1 = 'Hello World!’
2. for ch in str1:
3. print(ch,end = ‘ ')
Hello World! #output of for loop

✓ In the above code, the loop starts from the first character of the String str1 and automatically ends
when the last character is accessed.
33 Strings in Python | © SmartCliff | Internal | Version 1.0
Traversing a String

String traversal using for loop : Example #1

Trace Table
Line no
str1 ch ch in str1 Output

1 Hello World! Initial Value


2 H
2 H in str1→TRUE
3 H
2 e
2 e in str1→TRUE
3 e
2 l
2 l in str1→TRUE
3 l
34 Strings in Python | © SmartCliff | Internal | Version 1.0
Traversing a String

String traversal using for loop : Example #1

Trace Table
Line no
str1 ch ch in str1 Output

2 l
2 l in str1→TRUE
3 l
2 o
2 o in str1→TRUE
3 o
2 (space)
2 (space) in str1→TRUE
3 (space)
35 Strings in Python | © SmartCliff | Internal | Version 1.0
Traversing a String

String traversal using for loop : Example #1

Trace Table
Line no
str1 ch ch in str1 Output

2 W
2 W in str1→TRUE
3 W
2 o
2 o in str1→TRUE
3 o
2 r
2 r in str1→TRUE
3 r
36 Strings in Python | © SmartCliff | Internal | Version 1.0
Traversing a String

String traversal using for loop : Example #1

Trace Table
Line no
str1 ch ch in str1 Output

2 l
2 l in str1 →TRUE
3 l
2 d
2 d in str1→TRUE
3 d
2 !
2 ! in str1→TRUE
3 !
2 FALSE
37 Strings in Python | © SmartCliff | Internal | Version 1.0
Traversing a String

String traversal using for loop : Example #1

Sample Input and Output


HelloWorld!

38 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

String traversal using while loop : Example #2

Program
# Example: Iterating the sequence of elements using while loop.
1. 1.str1 = 'Hello World!’
2.index = 0
3.while index < len(str1):
4. print(str1[index],end = ‘’)
5. index += 1
✓ Use the len() function to determine the length of the String, then start at 0 and loop through the
String items by referring to their indexes.

39 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

String traversal using while loop : Example #2

Trace Table
Line no str1 index index<len(str1) Print index+=1

1 Hello World Initial Value


2 0 Initial Value
3 0 < len (11) →TRUE
4 H
5 1
2 1
3 1 < len (11) →TRUE
4 e
5 2
40 Strings in Python | © SmartCliff | Internal | Version 1.0
Traversing a String

String traversal using while loop : Example #2

Trace Table
Line no str1 index index<len(str1) Print index+=1

2 2
3 2 < len (11) →TRUE
4 l
5 3
2 3
3 3 < len (11) →TRUE
4 l
5 4

41 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

String traversal using while loop : Example #2

Trace Table
Line no str1 index index<len(str1) Print index+=1

2 4
3 4 < len (11) →TRUE
4 o
5 5
2 5
3 5 < len (11) →TRUE
4 (Space)
5 (space)

42 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

String traversal using while loop : Example #2

Trace Table
Line no str1 index index<len(str1) Print index+=1

2 6
3 6 < len (11) →TRUE
4 W
5 7
2 7
3 7 < len (11) →TRUE
4 o
5 o

43 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

String traversal using while loop : Example #2

Trace Table
Line no str1 index index<len(str1) Print index+=1

2 8
3 8 < len (11) →TRUE
4 r
5 9
2 9
3 9 < len (11) →TRUE
4 l
5 10

44 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

String traversal using while loop : Example #2

Trace Table
Line no str1 index index<len(str1) Print index+=1

2 10
3 10 < len (11) →TRUE
4 d
5 11
2 11
3 11 < len (11) →TRUE
4 !
5 12

45 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

String traversal using while loop : Example #2

Trace Table
Line no str1 index index<len(str1) Print index+=1

2 12
3 12 < len (11) →FALSE

46 Strings in Python | © SmartCliff | Internal | Version 1.0


Traversing a String

String traversal using while loop : Example #2

Sample Input and Output


HelloWorld!

47 Strings in Python | © SmartCliff | Internal | Version 1.0


STRING BUILT-IN
Functions

48 Strings in Python | © SmartCliff | Internal | Version 1.0


String Built-In Function

Built-In Function for String Manipulation

✓ Python has several built-in functions that allow us to work with strings.

✓ The below table describes some of commonly used built-in functions for string manipulations

Method Description Example

len() Returns the length of the String passed as the str1 = 'Hello World!’
argument print(len(str1))
12
title() Returns the String with first letterof every word in str1 = 'hello WORLD!’
the String in uppercase and rest in lowercase print(str1.title())
'Hello World!'

49 Strings in Python | © SmartCliff | Internal | Version 1.0


String Built-In Function

Built-In Function for String Manipulation

Method Description Example


lower() Returns the String with all uppercase letters str1 = 'hello WORLD!’
print(str1.lower())
converted to lowercase. 'hello world!'

upper() Returns the String with all lowercase letters str1 = 'hello WORLD!’
print(str1.upper())
converted to uppercase. 'HELLO WORLD!

count(str,start, Returns number of times subString str occurs in str1 = 'Hello World! Hello
end) Hello’
the given String. If we do not give start index print(str1.count('Hello',12,25))
and end index then searching starts from index 2
print(str1.count('Hello’))
0 and ends at length of the String 3

50 Strings in Python | © SmartCliff | Internal | Version 1.0


String Built-In Function

Built-In Function for String Manipulation

Method Description Example


find(str,start,end Returns the first occurrence of index of str1 = 'Hello World! Hello Hello’
) print(str1.find('Hello',10,20))
subString str occurring in the given String. If we 13
do not give start and end then searching starts print(str1.find('Hello',15,25))
19
from index 0 and ends at length of the String. If print(str1.find('Hello’))
the subString is not present in the given String, 0
print(str1.find('Hee’))
then the function returns -1. -1
index(str, Same as find() but raises an exception if the str1 = 'Hello World! Hello
start, end) Hello’
substring is not present in the given String. print(str1.index('Hello’))
0
print(str1.index('Hee’))
ValueError: subString not found
51 Strings in Python | © SmartCliff | Internal | Version 1.0
String Built-In Function

Built-In Function for String Manipulation

Method Description Example


endswith() Returns True if the given String ends with the str1 = 'Hello World!’
print(str1.endswith('World!’))
supplied substring otherwise returns False. True
print(str1.endswith('!’))
True
print(str1.endswith('lde’))
False
startswith() Returns True if the given String starts with the str1 = 'Hello World!’
print(str1.startswith('He’))
supplied substring otherwise returns False. True
print(str1.startswith('Hee’))
False

52 Strings in Python | © SmartCliff | Internal | Version 1.0


String Built-In Function

Built-In Function for String Manipulation

Method Description Example


isalnum() Returns True if characters of the given String are str1 = 'HelloWorld’
print(str1.isalnum())
either alphabets or numeric. If whitespace or True
special symbols are part of the given String or str1 = 'HelloWorld2’
print(str1.isalnum())
the string is empty it returns False. True
str1 = 'HelloWorld!!’
print(str1.isalnum())
False

53 Strings in Python | © SmartCliff | Internal | Version 1.0


String Built-In Function

Built-In Function for String Manipulation

Method Description Example


islower() Returns True if the String is non-empty and has str1 = 'hello world!’
print(str1.islower())
all lowercase alphabets, or has at least one True
character as lowercase alphabet and rest are str1 = 'hello 1234’
print(str1.islower())
non-alphabet characters. True
str1 = 'hello ??’
print*(str1.islower())
True
str1 = '1234’
print(str1.islower())
False
str1 = 'Hello World!’
print(str1.islower())
False
54 Strings in Python | © SmartCliff | Internal | Version 1.0
String Built-In Function

Built-In Function for String Manipulation

Method Description Example


isupper() Returns True if the String is non-empty and has str1 = 'HELLO WORLD!’
print(str1.isupper())
all uppercase alphabets, or has at least one True
character as uppercase character and rest are str1 = 'HELLO 1234’
print(str1.isupper())
non-alphabet characters. True
str1 = 'HELLO ??’
print(str1.isupper())
True
str1 = '1234’
print(str1.isupper())
False
str1 = 'Hello World!’
print(str1.isupper())
False
55 Strings in Python | © SmartCliff | Internal | Version 1.0
String Built-In Function

Built-In Function for String Manipulation

Method Description Example


isspace() Returns True if the String is non-empty and all str1 = ' \n \t \r’
print(str1.isspace())
characters are white spaces (blank, tab,newline, True
carriage return). str1 = 'Hello \n’
print(str1.isspace())
False
istitle() Returns True if the String is non-empty and title str1 = 'Hello World!’
print(str1.istitle())
case, i.e., the first letter of every word in True
the String in uppercase and rest in lowercase. str1 = 'hello World!’
print(str1.istitle())
False

56 Strings in Python | © SmartCliff | Internal | Version 1.0


String Built-In Function

Built-In Function for String Manipulation

Method Description Example


lstrip() Returns the String after removing the spaces str1 = ‘ Hello World!’
print(str1.lstrip())
only on the left of the String. 'Hello World! '

rstrip() Returns the String after removing the spaces str1 = ' Hello World!’
print(str1.rstrip())
only on the right of the String. ‘ Hello World!'

strip() Returns the String after removing the spaces str1 = ‘ Hello World! ‘
both on the left and the right of the String. print(str1.strip())
'Hello World!'

57 Strings in Python | © SmartCliff | Internal | Version 1.0


String Built-In Function

Built-In Function for String Manipulation

Method Description Example


replace(oldstr, Replaces all occurrences of old String with the str1 = 'Hello World!’
newstr) print(str1.replace('o','*’))
new String 'Hell* W*rld!'
str1 = 'Hello World!’
print(str1.replace('World','Country')
'Hello Country!'
str1 = 'Hello World! Hello’
print(str1.replace('Hello','Bye’))
'Bye World! Bye'
join() Returns a String in which the characters in the str1 = ('HelloWorld!')
str2 = '-’ #separator
String have been joined by a separator. print(str2.join(str1))
'H-e-l-l-o-W-o-r-l-d-!'

58 Strings in Python | © SmartCliff | Internal | Version 1.0


String Built-In Function

Built-In Function for String Manipulation

Method Description Example


index(str, Same as find() but raises an exception if the str1 = 'Hello World! Hello
start, end) Hello’
substring is not present in the given string. print(str1.index('Hello’))
0
str1.index('Hee')
ValueError: subString not found
split() Returns a list of words delimited str1 = 'India is a Great Country’
by the specified subString. If no print(str1.split())
delimiter is given then words are ['India','is','a','Great’, 'Country']
separated by space. str1 = 'India is a Great Country’
print(str1.split('a’))
['Indi', ' is ', ' Gre', ‘t Country']
59 Strings in Python | © SmartCliff | Internal | Version 1.0
String Built-In Function

Built-In Function for String Manipulation

Method Description Example


partition() Partitions the given String at the first occurrence str1 = 'India is a Great Country’
of the substring (separator) and returns the print(str1.partition('is’))
String partitioned into three parts. ('India ', 'is', ' a Great Country’)
1. SubString before the separator print(str1.partition('are’))
2. Separator ('India is a Great Country',' ',’ ')
3. SubString after the separator
If the separator is not found in the
String, it returns the whole String
itself and two empty Strings

60 Strings in Python | © SmartCliff | Internal | Version 1.0


STRING FORMATTING
IN PYTHON

61 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

What is String Formatting?

✓ String formatting is a way to insert a variable or another string in a predefined string.

✓ We can use various methods of string formatting in Python to manipulate strings.

✓ We can use format specifiers like other programming languages to perform string formatting. We can

also use the format() method and f-strings to manipulate strings in Python.

62 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using Format Specifiers

✓ Format specifiers are used with the % operator to perform string formatting and when invoked on a
string, takes a variable or tuple of variables as input and places the variables in the specified format
specifiers.

✓ Following is a table of the most commonly used format specifiers for different types of input variables.

Data Type of variable Format Specifiers


String %s

Single Character %c

Floating point Exponential %e

Floating point Decimal %f

Signed integer Decimal %d


63 Strings in Python | © SmartCliff | Internal | Version 1.0
String Formatting in Python

String Formatting using Format Specifiers

✓ In the below Example ,We put the format specifier in the predefined string at the position where the
variable is to be inserted. Then we insert the variable into the string using the % operator as follows –

# Format Specifier in the Predefined string


myCode = 1117
myName = "Smartcliff"
myVar = 1234
myStr = "Variable is {2} and Code of {0} is {1}".format(myName, myCode, myVar)
print(myStr)
# Output: Variable is 1234 and Code of Smartcliff is 1117

64 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using Format Specifiers

✓ We will specify the desired number of format specifiers to insert two or more variables into the
string.

✓ Then we will pass a tuple of variables as input to the % operator at the specified positions in a serial
manner as follows.

myCode = 1117
myName = "Smartcliff"
myStr = "Code of %s is %d" % (myName, myCode)
print(myStr)
# Output: Code of Smartcliff is 1117

65 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using Format Specifiers

✓ Specifying variables with the correct data type for each format specifier is important. Otherwise,
the TyperError exception is raised as follows.

myCode = 1117
myName = "Smartcliff"
myStr = "Code of %s is %d" % (myCode,myName)
print(myStr)
# Output: Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
myStr = "Code of %s is %d" % (myCode,myName)
TypeError: %d format: a number is required, not str

66 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using Format Specifiers

✓ Specifying the correct number of variables, equal to the number of format specifiers if we insert
more than one variable into the string, is also essential. Inserting variables less than or greater
than the number of format specifiers will again lead to the TypeError exception.

myCode = 1117
myName = "Smartcliff"
myVar=123
myStr = "Code of %s is %d" % (myName,myCode, myVar)
print(myStr)
# output: Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 4, in <module>
myStr = "Code of %s is %d" % (myName,myCode, myVar)
TypeError: not all arguments converted during string formatting

67 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using f-string

✓ Formatted strings or f-strings are string literals that can be used directly to insert variables into

predefined strings.

✓ To format strings using f-strings, We only need to put variable names into placeholders made using

curly braces “{ }”.

✓ The value of the variables defined in the placeholders is automatically updated by the Python

interpreter upon execution of the program as follows:

68 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using f-string

myCode = 1117
myName = "Smartcliff"
myStr = f"Code of {myName} is {myCode}"
print(myStr)
# Output: Code of Smartcliff is 1117

✓ f-strings have an advantage over format specifiers: we don’t need to worry about data types of
input variables. We also don’t need to worry about the order of input variables as we have to
specify variable names directly into the placeholders.

69 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using format() method

✓ Another way to format strings in Python is to use the format() method.

✓ In this method, first, we put placeholders in the string in which the variables are to be inserted. Then
we invoke the format method on the string with variables that have to be inserted into the string
as input arguments.

✓ The Syntax of the format() is

myString.format(val1, val2,…. ,valN)

✓ Here, myString is the string containing placeholders for the variables to be inserted. Val1, val2, val3

upto valN are the input variables to be inserted into myString.

70 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using format() method

✓ After execution, the variables are serially placed in the placeholders as follows.

myCode = 1117
myName = "Smartcliff"
myStr = "Code of {} is {}".format(myName,myCode)
print(myStr)
# Output: Code of Smartcliff is 1117

71 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using format() method

✓ In the format() method, if we pass input arguments greater than the number of placeholders in

myString, Only the variables equal to the number of placeholders are inserted into the string, and

the rest of the input arguments are ignored as follows.

myCode = 1117
myName = "Smartcliff"
myVar=1234
myStr = "Code of {} is {}".format(myName,myCode,myVar)
print(myStr)
# Output: Code of Smartcliff is 1117

72 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

String Formatting using format() method

✓ If we pass variables less than the number of placeholders in myString, IndexError occurs as

follows.

myCode = 1117
myName = "Smartcliff"
myVar=1234
myStr = "Code of {} is {}".format(myName)
print(myStr)
# Output : Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 4, in <module>
myStr = "Code of {} is {}".format(myName)
IndexError: Replacement index 1 out of range for positional args tuple

73 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

How Does the format() method work in Python?

✓ The format() method can take input arguments in three ways as follows:

1. Working with Default Arguments

2. Working with Positional Arguments

3. Working with Keyword Arguments

74 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Working with Default Arguments

✓ The default way the format() method takes input is that we simply pass the variables as input

arguments.

✓ When the method is invoked on a string, it places the values in the corresponding placeholders in

the string one by one.

✓ In this case, we have to pass the input arguments in the same order they have to be inserted into

the string.

75 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Working with Default Arguments

# Example : insert a string and an integer variable into a string using default arguments
myCode = 1117
myName = "Smartcliff"
myVar=1234
myStr = "Code of {} is {}".format(myName,myCode)
print(myStr)
# Output:Code of Smartcliff is 1117

76 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Working with Positional Arguments

✓ Instead of empty placeholders, we can use the positions of the input arguments while inserting them

into the string.

✓ We fill the index of input variables, in the placeholders, in the string, and during execution, the input

arguments are inserted into the string according to their positions.

✓ In this method, we are not required to pass the input arguments in the same order they have to be

inserted into the string.

77 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Working with Positional Arguments

# Example : insert a string and an integer variable into a string using positional arguments
myCode = 1117
myName = "Smartcliff"
myVar = 1234
myStr = "Variable is {2} and Code of {0} is {1}".format(myName, myCode, myVar)
print(myStr)
# Output:Variable is 1234 and Code of Smartcliff is 1117

78 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Working with Keyword Arguments

✓ We can also use keyword arguments in the format() method for string formatting in Python.

✓ In this method, we define keywords in the placeholders and then pass the input variables as

keyword arguments as follows.

✓ In this method, we are not required to pass the input arguments in the same order the keywords

have been specified.

✓ This method gives us better flexibility and we can use the variable by placing the keyword

anywhere in the string, irrespective of the position at which it has been defined in the input.

79 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Working with Keyword Arguments

myCode = 1117
myName = "Smartcliff"
myVar = 1234
myStr = "Variable is {myVar} and Code of {myName} is {myCode}".format(myName, myCode, myVar)
print(myStr)
# Output: Variable is 1234 and Code of Smartcliff is 1117

80 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Alignment of strings using format() method

✓ For the alignment of strings, we use the same syntax we used for the alignment of numbers.

✓ To left-align a string, we use the “:<n” symbol inside the placeholder. Here n is the total length of
the required output string.

myString = "Smartcliff"
myStr = "Left Aligned String with length 10 is: {:<10}.".format(myString)
print(myStr)
# Output:Left Aligned String with length 10 is: Smartcliff .

81 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Alignment of strings using format() method

✓ To right align a string, we use the “:>n” symbol inside the placeholder. Here n is the total length of
the required output string.
myString = "Smartcliff"
myStr = "Right Aligned String with length 10 is: {:>10}.".format(myString)
print(myStr)
# Output: Right Aligned String with length 10 is: Smartcliff.

✓ To center align a string, we use the “:^n” symbol inside the placeholder. Here n is the total length
of the required output string.
myString = "Smartcliff"
myStr = "Center Aligned String with length 10 is: {:^10}.".format(myString)
print(myStr)
# Output: Center Aligned String with length 10 is: Smartcliff .

82 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Truncating the strings using format() method

✓ To truncate a string to a specific length, we use the symbol “:.n” inside the placeholder of the
empty string at which the format() method is invoked. Then we pass the input string as the argument
to the format() method as follows: Here, n is the required output length.

myString = "Smartcliff"
myStr = "Truncated String with length 3 is: {:.3}".format(myString)
print(myStr)
# Output: Truncated String with length 3 is: Sma

83 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Padding the strings using format() method

✓ Alignment is a specific type of padding in which the padding character is the space character. Here
we assume that we have to pad the strings using the * character.

✓ To pad a string on the left side with , we use the “:<n” symbol inside the placeholder. Here n is the
total length of the required output string.

myString = "Smartcliff"
myStr = "Padded String with string on left and length 20 is: {:*<20}".format(myString)
print(myStr)
# Output: Padded String with string on left and length 20 is: Smartcliff**************

84 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python

Padding the strings using format() method

✓ To pad a string on the right side, we use the “:*>n” symbol inside the placeholder. Here n is the
total length of the required output string.
myString = "Smartcliff"
myStr = "Padded String with string on right and length 20 is: {:*>20}".format(myString)
print(myStr)
# Output: Padded String with string on right and length 20 is: **************Smartcliff

✓ To pad a string keeping the input string in the center, we use the “:*^n” symbol inside the
placeholder. Here n is the total length of the required output string.
myString = "Smartcliff"
myStr = "Padded String with string on center and length 20 is: {:*^20}".format(myString)
print(myStr)
# Output:Padded String with string on center and length 20 is: *******Smartcliff*******
85 Strings in Python | © SmartCliff | Internal | Version 1.0
String Formatting in Python

Dynamic Formatting using the format() method

✓ Until now, we have used only those formatting types in which the output string size was fixed.

✓ To dynamically set the size of the output string, we can pass the size as input to the format()
method.

✓ For this, we will use an extra placeholder for the size of the output string inside the placeholder for
the input string.

✓ To left-align a string, we use the “:<n” symbol inside the placeholder. Here “n” is the total length of
the required output string.

86 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python
Dynamic Formatting using the format() method

✓ To dynamically set the size of the output string, we can insert a placeholder in place of “n” and
pass the value “n” as input to the format() method as follows:

myString = "Smartcliff"
length = 20
myStr = "Dynamically Left Aligned String is: {:<{}}".format(myString, length)
print(myStr)
# Output: Dynamically Left Aligned String is: Smartcliff

87 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python
Dynamic Formatting using the format() method

myString = “Smartcliff"
length = 20
myStr = "Dynamically Right Aligned String is: {:>{}}.".format(myString, length)
print(myStr)
myStr = "Dynamically Center Aligned String is: {:^{}}.".format(myString, length)
print(myStr)
myStr = "Dynamically Padded String with input on left is: {:*<{}}.".format(myString, length)
print(myStr)
myStr = "Dynamically Padded string with input on right is: {:*>{}}.".format(myString, length)
print(myStr)
myStr = "Dynamically Padded string with input on center is: {:*^{}}.".format(myString, length)
print(myStr)
myStr = "Dynamically truncated String with output length 3 is: {:.{}}.".format(myString, 3)
print(myStr)
88 Strings in Python | © SmartCliff | Internal | Version 1.0
String Formatting in Python
Dynamic Formatting using the format() method

# Output:
Dynamically Right Aligned String is: Smartcliff.
Dynamically Center Aligned String is: Smartcliff .
Dynamically Padded String with input on left is: Smartcliff**************.
Dynamically Padded string with input on right is: **************Smartcliff.
Dynamically Padded string with input on center is: *******Smartcliff*******.
Dynamically truncated String with output length 3 is: Sma.

✓ When the specified output length is less than the input string length, the input string is not
altered during the alignment and padding. In case of truncating, the output string is truncated to
the required output length. This can be observed in the following example.

89 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python
Dynamic Formatting using the format() method

myString = "Smartcliff"
length = 2
myStr = "Dynamically Right Aligned String is: {:>{}}.".format(myString, length)
print(myStr)
myStr = "Dynamically Padded string with input on right is: {:*>{}}.".format(myString, length)
print(myStr)
myStr = "Dynamically truncated String with output length 3 is: {:.{}}.".format(myString, 3)
print(myStr)
# Output: Dynamically Right Aligned String is: Smartcliff.
Dynamically Padded string with input on right is: Smartcliff.
Dynamically truncated String with output length 3 is: Sma.

90 Strings in Python | © SmartCliff | Internal | Version 1.0


String Formatting in Python
Dynamic Formatting using the format() method

✓ However, when the given output length is negative, ValueError will occur with a message
“ValueError: Sign not allowed in string format specifier” as seen below.

myString = "Smartcliff"
length = -10
myStr = "Dynamically Right Aligned String is: {:>{}}.".format(myString, length)
print(myStr)
myStr = "Dynamically Padded string with input on right is: {:*>{}}.".format(myString, length)
print(myStr)
# Output:Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string.py", line 3, in <module>
myStr = "Dynamically Right Aligned String is: {:>{}}.".format(myString, length)
ValueError: Sign not allowed in string format specifier

91 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

1. What data type is used to store textual data in Python?

a) str

b) string

c) text

d) char

Answer : Option a)

92 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

2. Which of the following is a valid way to create a string in


Python?

a) 'Hello World'

b) "Hello World"

c) '''Hello World'''

d) All of the above

Answer : Option d)

93 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

3. How do you repeat a string s five times in Python?

a) s * 5

b) repeat(s, 5)

c) s.repeat(5)

d) s.repeat(5)

Answer : Option a)

94 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

4. How do you access the first character of a string s in


Python?

a) s[0]

b) s.first()

c) first(s)

d) s.charAt(0)

Answer : Option a)

95 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

5. Which method in Python returns the number of


occurrences of a substring in a string?

a) count()

b) find()

c) index()

d) replace()

Answer : Option a)

96 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

6. What does the split() method do in Python?

a) Splits the string into a list of characters

b) Splits the string based on whitespace and returns a


list of words

c) Removes leading and trailing whitespace from the


string

d) Joins a list of strings into a single string

Answer : Option b)

97 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

7. How do you access the last character of a string s in


Python?

a) s[len(s)]

b) s[-1]

c) s.last()

d) s.charAt(len(s) - 1)

Answer : Option b)

98 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

8. Which method is used to find the index of the first


occurrence of a substring in a string in Python?

a) index()

b) find()

c) locate()

d) search()

Answer : Option b)

99 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

9. What does the following code snippet do?


s = "hello"
print(len(s))

a) Prints the number of words in the string

b) Prints the length of the string

c) Converts the string to uppercase

d) Converts the string to lowercase

Answer : Option b)

100 Strings in Python | © SmartCliff | Internal | Version 1.0


Strings in Python

Check your understanding

10. Which of the following is the correct way to concatenate


the strings s1 and s2 in Python?

a) s1.concat(s2)

b) s1 & s2

c) s1 + s2

d) concat(s1, s2)

Answer : Option c)

101 Strings in Python | © SmartCliff | Internal | Version 1.0


THANK YOU

You might also like