0% found this document useful (0 votes)
5 views30 pages

Python String Methods Explained

The document provides an overview of Python string methods, including accessing characters, slicing, testing, modifying, and searching strings. It emphasizes the importance of practice in programming and covers various string operations such as concatenation, repetition, and splitting. Additionally, it includes examples and quizzes to reinforce the concepts discussed.

Uploaded by

Shivam Kerwal
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)
5 views30 pages

Python String Methods Explained

The document provides an overview of Python string methods, including accessing characters, slicing, testing, modifying, and searching strings. It emphasizes the importance of practice in programming and covers various string operations such as concatenation, repetition, and splitting. Additionally, it includes examples and quizzes to reinforce the concepts discussed.

Uploaded by

Shivam Kerwal
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

FUNDAMENTALS OF

PYTHON

Surbhi Chhabra
Assistant Professor, JKLU, Jaipur
OVERVIEW
▪ We will explore :
• Python Strings Methods

P R A C T I C E , P R A C T I C E , PRACTICE
The best way to improve your programming and problem
skills is to practice!

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 2


ACCESSING THE INDIVIDUAL CHARACTERS IN A STRING
Iterating over a String with the for Loop (loop iterates over the characters in the
string) :
for variable in string:
statement
statement
etc.

Example:
name = ‘JKLU12' Note: If we change the value that ch references in the loop, it has no effect on the
for ch in name: string referenced by name.

print(ch) name = ‘JKLU12'


for ch in name:
J ch = 'X'
print(name)
K
L The statement in line 3 merely reassigns the ch variable to a different value each
U time the loop iterates. It has no effect on the string ‘JKLU12' that is referenced by
1 name, and it has no effect on the number of times the loop iterates. When this
code executes, the statement in line 4 will print:
2 JKLU12

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 3


ACCESSING THE INDIVIDUAL CHARACTERS IN A STRING

• Each character in a string has an index that specifies its position in the string.

• Indexing starts at 0, so the index of the first character is 0, the index of the second
character is 1, and so forth. The index of the last character in a string is 1 less than
the number of characters in the string.

• You can also use negative numbers as indexes, to identify character positions
relative to the end of the string. The Python interpreter adds negative indexes to
the length of the string to determine the character position.

• The index −1 identifies the last character in a string, −2 identifies the next to last
character, and so forth.

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 4


ACCESSING THE INDIVIDUAL CHARACTERS IN A STRING

my_string = 'Roses are red'


ch = my_string[6] a
print(my_string[0], my_string[6], my_string[10]) R a r
print(my_string[−1], my_string[−2], my_string[−13]) d e R

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 5


INDEX ERROR EXCEPTIONS
• An Index Error exception will occur if you try to use an index that is out of range for a
particular string.

• This type of error is most likely to happen when a loop incorrectly iterates beyond the end
of a string, as shown here:

city = ‘London'
index = 0
while index < 7:
print(city[index])
index += 1

• The last time that this loop iterates, the index variable will be assigned the value 6, which
is an invalid index for the string ‘London'. As a result, the print function will cause an Index
Error exception to be raised.

• The len function is especially useful to prevent loops from iterating beyond the end of a
string, as shown here:

city = ‘London'
index = 0
while index < len(city):
print(city[index])
Index += 1
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 6
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 7
STRING SLICING
• You can use slicing expressions to select a range of characters from a string. String
slices are also called substrings.

• To get a slice of a string, you write an expression in the following general format:
string[start : end]

• In the general format, start is the index of the first character in the slice, and end is
the index marking the end of the slice. The expression will return a string containing
a copy of the characters from start up to (but not including) end.

• E.g. helloString=“Hello World”


• Print(helloString[6:10]) Worl
• Print(helloString[3:-2]) lo Wor

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 8


STRING SLICING

Print(helloString[::2]) HloWrd

full_name = 'Patty Lynn Smith'


middle_name = full_name[6:10] Lynn
first_name = full_name[:5] Patty
last_name = full_name[11:] Smith
my_string = full_name[:] Patty Lynn Smith
my_string = full_name[0 : len(full_name)] Patty Lynn Smith
last_name = full_name[−5:] Smith

letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(letters[0:26:2]) ACEGIKMOQSUWY

The third number inside the brackets is the step value. A step value of 2, as used in this
example, causes the slice to contain every second character from the specified range in
the string. The code will print the following: ACEGIKMOQSUWY

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 9


STRING PRESENTATION TYPES
• Integers
The d presentation type formats integer values as strings:
print(f'{10:d}’)
10
There also are integer presentation types (b, o and x or X) that format integers using
the binary, octal or hexadecimal number systems.

• Characters
The c presentation type formats an integer character code as the corresponding
character:
print(f'{65:c} {97:c}’)
Aa

• Strings
The s presentation type is the default.
print(f'{"hello":s} {7}’)
hello 7
In this snippet, "hello" is enclosed in double quotes. Note that you cannot place single
quotes inside a single-quoted string.
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 10
STRING PRESENTATION TYPES
• Explicitly Specifying Left and Right Alignment in a Field: We can specify left and
right alignment with < and >:
print(f'[{27:<15d}]’)
[27 ]

print(f'[{3.5:<15f}]’)
[3.500000 ]

print(f'[{"hello":>15}]’)
[ hello]

• Centering a Value in a Field: We can center values:


print(f'[{27:^7d}]’)
[ 27 ]

print(f'[{3.5:^7.1f}]')
[ 3.5 ]

print(f'[{"hello":^7}]’)
[ hello ]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 11
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 12
STRING TESTING : WITH IN AND NOT IN
• In Python, you can use the in operator to determine whether one string is contained
in another string.

• We can use the not in operator to determine whether one string is not contained in
another string.

• Here is the general format of an expression using the in operator with two strings:
string1 in string2

text = 'Four score and seven years ago'


if 'seven' in text:
print('The string "seven" was found.’) The string "seven" was found
else:
print('The string "seven" was not found.')

names = ‘Python is amazing'


if ‘Language' not in names:
print(‘Please add this word’) Please add this word
else:
print(‘we have found the word')

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 13


STRING TESTING
• Python provides string methods for testing whether a string
matches certain characteristics.
• For example, string method isdigit returns True if the string on which you call the
method contains only the digit characters (0–9).
A= '-27'.isdigit( )
print(A) False
A= 27'.isdigit( )
print(A) True

• The string method isalnum returns True if the string on which you call the method is
alphanumeric—that is, it contains only digits and letters:
A= 'A9876'.isalnum( )
print(A) True
A= '123 Main Street'.isalnum( )
print(A) False

The swapcase() method returns a string where all the upper case letters are lower case
and vice versa.
txt = "Hello My Name Is HARRY"
x = [Link]()
print(x) hELLO mY nAME iS harry
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 14
STRING TESTING

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 15


STRING MODIFICATIONS
letters = 'WXYZ'
print(letters, [Link]( )) WXYZ wxyz

letters = 'abcd'
print(letters, [Link]( )) abcd ABCD

Changing Character Case


We can change a string’s capitalization with methods capitalize and title.

Capitalizing Only a String’s First Character: Method capitalize copies the


original string and returns a new string with only the first letter capitalized
(this is sometimes called sentence capitalization).
A= 'happy birthday'.capitalize( )
Print(A) Happy birthday

Capitalizing the First Character of Every Word in a String: Method title copies
the original string and returns a new string with only the first character of
each word capitalized (this is sometimes called book-title capitalization).
A= 'strings: a deeper look'.title( )
Print(A) Strings: A Deeper Look
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 16
STRING MODIFICATIONS

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 17


STRING SEARCHING AND REPLACING

filename = input('Enter the filename: ')


if [Link]('.txt'):
print('That is the name of a text file.')
elif [Link]('.py'):
print('That is the name of a Python source file.')
elif [Link]('.doc'):
print('That is the name of a word processing document.')
else:
print('Unknown file type.')
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 18
STRING SEARCHING AND REPLACING
string = 'Four score and seven years ago'
position = [Link]('seven')
if position != −1:
print(f’The word “seven” was found at index {position}.’)
else:
print('The word "seven" was not found.’)
The word "seven" was found at index 15.

string = 'Four score and seven years ago'


new_string = [Link]('years', 'days')
print(new_string)
Four score and seven days ago

Counting Occurrences
String method count returns the number of times its argument occurs in the
string on which the method is called:
sentence = 'to be or not to be that is the question’
print([Link]('to’))
2

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 19


STRING CONCATENATION
• appending one string to the end of another string
• The + operator produces a string that is the combination of the two strings used as its
operands.

letters = 'abc'
letters += 'def'
print(letters) abcdef

• Strings Are Immutable: which means once they are created, they cannot be changed.
Some operations, such as concatenation, give the impression that they modify strings,
but in reality they do not.

name = ‘Harry'
print(f'The name is: {name}’) Harry
name = name + ‘Potter'
print(f'Now the name is: {name}’) Harry Potter

Here, the original string ‘Harry' is not modified. Instead, a new string containing ‘Harry
Potter' is created and assigned to the name variable. (The original string, ‘Harry' is no
longer usable because no variable references it. The Python interpreter will eventually
remove the unusable string from memory.)

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 20


STRING REPETITION
• We can duplicate a list with the repetition operator (*). The repetition
operator works with strings as well. Here is the general format:
string_to_copy * n

• print('Hello' * 5) HelloHelloHelloHelloHello

• # Print nine rows increasing in length.


for count in range(1, 10):
print('Z' * count)

• # Print nine rows decreasing in length.


for count in range(8, 0, −1):
print('Z' * count)

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 21


Programming-1(Python) [Link]. First Sem Surbhi Chhabra 22
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 23
STRING SPLIT
• Strings in Python have a method named split that returns a list containing
the words in the string.

# Create a string with multiple words.


my_string = 'One two three four'
# Split the string.
word_list = my_string.split( )
# Print the list of words.
print(word_list) ['One', 'two', 'three', 'four’]

• By default, the split method uses spaces as separators (that is, it returns a
list of the words in the string that are separated by spaces).
• We can specify a different separator by passing it as an argument to the
split method. For example, suppose a string contains a date, as shown here:
date_string = '11/26/2020'
• If you want to break out the month, day, and year as items in a list, you can
call the split method using the '/' character as a separator, as shown here:
date_list = date_string.split('/')
• After this statement executes, the date_list variable will reference this list:
['11', '26', '2020']

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 24


CLASS QUIZ
• x='India'
• print(x=='India')
• print(x=='india')
• print('apple' > 'one') #it gives output false because it compares first letter of
both the strings
• print('four' < 'ten') # it gives output true because they compare first letter of
both strings
• print('ab'<'az') # as first letter is same than it goes to second letter b is less
than z
• print('abcde' > 'abcdef') # f cannot be less than nothing therefore output is
false

• #chaining operator: when we use multiple relational operator in the single


statement, then it is called chaining operators.
• x=5
• print( 1 < x < 10) #output either will be true or false
• print(10 < x < 20)
• print(x < 10 < x * 10 < 100)
• print(10 > x <= 9)
• print(5 == x > 4)
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 25
CLASS QUIZ
x='pytHoN sTrIng mEthOdS'
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
x='python'
print([Link]())
x='Python'
print([Link]())
x='PYTHON'
print([Link]())
x='PYTHoN'
print([Link]())
x='Python String Methods'
print([Link]())
x='Python string methods'
print([Link]())
x='123'
print([Link]())
x='123abc'
print([Link]())

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 26


CLASS QUIZ
x='abc'
print([Link]())
x='abc123'
print([Link]())
x='abc123'
print([Link]())
x='abc123#@'
print([Link]())
x='---Python---'
print([Link]('-'))
print([Link]('-'))
print([Link]('-'))
x='Python'
print([Link]('P'))
print([Link]('p'))
print([Link]('n'))
print([Link]('N'))
x='Python String Methods'
print([Link]('t'))
print([Link]('s'))
print([Link]('t'))
print([Link]('s’))
print([Link]('S', 's'))
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 27
CLASS QUIZ
num=int(input('enter no.:'))
for i in range(1,11):
print(num, 'X', i, '=', num * i)
print(f'{num} X {i} = {num * i}’ ) #formatted print statement and inside the
curly bracket computer will recognized them as variable otherwise it is string.
print('{0} X {1}= {2}'.format(num, i, num*i)) #print using format function
print('%d X %d = %d' %(num, i, num*i)) #old way of writing print statement,
c programming used to follow this. 'd' stands for integer. %d will be replaced
by num, second by i and third percent d will be replaced by num*i.
#The above print statement is also known as print using string modulo
operator because actual string and values are separated using modulo
operator.

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 28


JOINING STRINGS
• String method join( ) concatenates the strings in its argument, which must
be an iterable containing only string values; otherwise, a TypeError occurs.

• The join( ) method takes all items in an iterable and joins them into one
string. A string must be specified as the separator.

• letters_list = ['A', 'B', 'C', 'D’]


• print(','.join(letters_list)) A,B,C,D

• a= ','.join([str(i) for i in range(10)])


• print(a) 0,1,2,3,4,5,6,7,8,9

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 29


HOW TO REVERSE STRING IN PYTHON
• There is no built-in function to reverse a String in Python. The fastest way is
to use a slice that steps backwards, -1.

• txt = "Hello World"[: : -1]


• print(txt) dlroW olleH

• In the above example, We are creating a slice that starts at the end of the
string, and moves backwards. In this particular example, the slice statement
[: : -1] means start at the end of the string and end at position 0, move with
the step -1, negative one, which means one step backwards.

• txt = "Hello World"


• txt=[Link]()
• words= txt[: : -1]
• print(txt) ['Hello', 'World']
• print(words) ['World', 'Hello']

Programming-1(Python) [Link]. First Sem Surbhi Chhabra 30

You might also like