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

Python String Basics and Operations

Uploaded by

Het Patel
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 views29 pages

Python String Basics and Operations

Uploaded by

Het Patel
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

FET – B.

Tech (CS & E)

Computer Programming Paradigm (Python)


(2601102)

h
Unit 2.3 String
c
Te
.
BDr. Tejaskumar Bhatt
T
Prepared By:
E
F )
S
L &E
G S
(C
Reference:
• Rao, R. N. (2009). Core Python programming (2nd ed.). Dreamtech Press
• Chun, W. (2007). Core Python programming (1st ed.). Pearson.
• Lutz, M. (2013). Learning Python (5th ed.). O'Reilly Media.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

String
 A string represents a group of characters.
 Strings are important because most of the data that we use in daily life will be in
the form of strings.
 For example, the names of persons, their addresses, vehicle numbers, their credit
card numbers, etc. are all strings.
 In Python, the str datatype represents a string.

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Creating String
 Create a string in Python by assigning a group of characters to a variable.
 The group of characters should be enclosed inside single quotes or double quotes.
 s1 = 'Welcome to Core Python learning'
 print(s1)
 s2 = "Welcome to Core Python learning"

h
 There is no difference between the single quotes and double quotes while creating

ec
the strings. Both will work in the same manner.

.T
B
 Sometimes, we can use triple single quotes or triple double quotes to represent

E) T
strings. These quotation marks are useful when we want to represent a string that

S& FE
occupies several lines.
 str3 = '''Welcome to Core Python, a book on Python language that discusses all
(C LS
important concepts of Python in a lucid and comprehensive manner.'''
G

 str4 = """Welcome to Core Python, a book on Python language that discusses all
important concepts of Python in a lucid and comprehensive manner."""
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

String

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Creating String
 To create a string with Unicode characters, we should add ‘u’ at the beginning of
the string.
 Unicode is a standard to include the alphabet of various human languages into
programming languages like Python or Java.
 For example, it is possible to display the alphabet of Hindi, French, and German

h
languages using Unicode system.

ec
 Each Unicode character contains 4 digits preceded by a \u.

.T
B
 The following statement displays ‘Core Python’ in Hindi using Unicode characters.

E) T
There are 9 Unicode characters used(including space) for this purpose.

S& FE
name = u'\u0915\u094b\u0930\u0020\u092a\u0948\u0925\u0964\u0928'
(C LS
 print(name)
G

 Output: कोर पैथ।न

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Length of a String
 Length of a string represents the number of characters in a string.
 To know the length of a string, we can use the len() function.
 This function gives the number of characters including spaces in the string.
str = 'Core Python'

h
n = len(str)

ec
print(n)

.T
B
 Output:11

E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Indexing in Strings
 Index represents the position number.
 Index is written using square braces [].
 By specifying the position number through an index, we can refer to the individual
elements (or characters) of a string.
 For example, str[0] refers to the 0th element of the string and str[1] refers to the 1st

h
ec
element of the string.

.T
 Thus, str[i] can be used to refer to ith element of the string.

B
 Here, ‘i’ is called the string index because it is specifying the position number of

E) T
the element in the string.
S& FE
 When we use index as a negative number, it refers to elements in the reverse
(C LS
order. Thus, str[-1] refers to the last element and str[-2] refers to second element
from last.
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String

 The format of slicing is stringname[start: stop: stepsize].


 If ‘start’ and ‘stop’ are not specified, then it is taken from 0th to n-1th elements.
 If ‘stepsize’ is not written, then it is taken to be 1.
 Hence, the following loop will display all the elements of the string:
for i in str[: : ]: # do not mention start, stop and stepsize

h
ec
print(i)

.T
B
 To get the elements in reverse order, we should use stepsize negative as: -1.

E) T
S& FE
 This will display the elements from last to first in steps of 1 in reverse order.
(C LS
 The for loop in this case looks like this:
G

for i in str[: : -1]: # take stepsize as -1


print(i)

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
A Python program to access the characters of a string using for loop.
# accessing elements of a string using for loop
str = 'Core Python'
for i in str: # access each letter using for loop
print(i, end=' ')

h
print() # put cursor into next line

ec
for i in str[:: -1]: # access in reverse order

.T
print(i, end=' ')

B
E) T
 O/P:
S& FE
C:\>python [Link]
(C LS
Core Python
G

nohtyPeroC

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Slicing the Strings
 A slice represents a part or piece of a string. The format of slicing is:
 stringname[start: stop: stepsize]
str = 'Core Python'
str[0:9:1] # access string from 0th to 8th element in steps of 1
 O/P: Core Pyth

h
ec
.T
 When ‘stepsize’ is 2, then it will access every other character from 1 st character

B
onwards. Hence it retrieves the 0th, 2nd, 4th , 6th characters and so on.

E) T
S& FE
 str[0:9:2]
 O/P: Cr yh
(C LS
G

 Str[2:4:1] # access from str[2] to str[3] in steps of 1


 Output: re
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

String
Slicing the Strings
 Str[::2] # access entire string in steps of 2
 Output: Cr yhn

 Str[2::] # access string from str[2] to ending


 Output:

h
re Python

ec
.T
 Str[:4:] # access string from str[0] to str[3] in steps of 1

B
 Output:

E) T
Core

S& FE
(C LS
 str = 'Core Python'
G

 str[-4:-1] # access from str[-4] to str[-2] from left to right in str.


 Output: tho

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Slicing the Strings
 Str[-6::] # access from str[-6] till the end of the string
 Output: Python

 Str[-1:-4:-1] # retrieve from str[-1] to str[-3] from right to left


 Output: 'noh'

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Repeating the Strings
 The repetition operator is denoted by ‘*’ symbol and is useful to repeat the string
for several times.
 For example, str * n repeats the string for n times. See the example:
 str = 'Core Python'
 print(str*2)

h
ec
 Output: Core PythonCore Python

.T
B
 Similarly, it is possible to repeat a part of the string obtained by slicing as:

E) T
S& FE
 s = str[5:7]*3 # repeat 5th 6th characters for 3 times
 print(s)
(C LS
 Output: PyPyPy
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Concatenation of Strings
 We can use ‘+’ on strings to attach a string at the end of another string.
 This operator ‘+’ is called addition operator when used on numbers.
 But, when used on strings, it is called ‘concatenation’ operator since it joins or
concatenates the strings.
 Similar result can be achieved using the join() method also.

h
ec
 s1='Core'

.T
 s2="Python"

B
 s3=s1+s2 # concatenate s1 and s2

E) T
S& FE
 print(s3) # display the total string s3
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Checking Membership
 We can check if a string or character is a member of another string or not using
‘in’ or ‘not in’ operators.
 The not in Operator
 The in Operator
 It checks if something exists inside a string.  It is the opposite of in.
 If it is found → returns True.  If it is not found → returns True.
 If not found → returns False.  If found → returns False.

h
ec
.T
B
 # to know whether sub string is in main string or not

E) T
 str = input('Enter main string: ')

 if sub in str:
S& FE
sub = input('Enter sub string: ') C:\>python [Link]
(C LS
Enter main string: This is Core Python
 print(sub+' is found in main string') Enter sub string: Core
G

 else: Core is found in main string


 print(sub+' is not found in the main string')

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Comparing Strings
 The relational operators like >, >=, <, <=, == or != operators to compare two
strings. They return Boolean value, i.e. either True or False depending on the
strings being compared.
s1='Box' if s1<s2:
s2='Boy' print('s1 less than s2')
if(s1==s2): else:

h
print('Both are same') print('s1 greater than or equal to s2')

ec
else:

.T
print('Not same')

B
 This code returns ‘Not same’ as the strings are not same. While comparing the

E) T
strings, Python interpreter compares them by taking them in English dictionary
order.
S& FE
 The string which comes first in the dictionary order will have a low value than the
(C LS
string which comes next. It means, ‘A’ is less than ‘B’ which is less than ‘C’ and so
G

on.
 In the above example, the string ‘s1’ comes before the string ‘s2’ and hence s1 is
less than s2.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

String
Removing Spaces from a String
 A space is also considered as a character inside a string. Sometimes, the
unnecessary spaces in a string will lead to wrong results.
 For example, a person typed his name ‘TejasBhatt‘ (observe two spaces at the end
of the string) instead of typing ‘TejasBhatt’.
 If we compare these two strings using ‘==’ operator as:
 if

h
'TejasBhatt '== 'TejasBhatt':

ec
 print('Welcome')

.T
 else:

B
 print('Name not found')

E) T
 The output will be ‘Name not found’.

S& FE
 In this way, spaces may lead to wrong results.
(C LS
 Hence such spaces should be removed from the strings before they are compared.
G

 This is possible using rstrip(), lstrip() and strip() methods.

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Removing Spaces from a String
 The rstrip() method removes the spaces which are at the right side of the string.
 The lstrip() method removes spaces which are at the left side of the string.
 The strip() method removes spaces from both the sides of the strings.
 These methods do not remove spaces which are in the middle of the string.
 name = ' TejasBhatt ' #observe spaces before and after the name

h
ec
 print([Link]()) # remove spaces at right

.T
 print([Link]()) # remove spaces at left

B
 print([Link]()) # remove spaces from both sides

E) T
S& FE
 Output: TejasBhatt (C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Finding Sub Strings
 The find(), rfind(), index() and rindex() methods are useful to locate sub strings in a
string.
 These methods return the location of the first occurrence of the sub string in the
main string.
 The find() and index() methods search for the sub string from the beginning of the

h
main string.

ec
 The rfind() and rindex() methods search for the sub string from right to left, i.e. in

.T
backward order.

B
 The find() method returns -1 if the sub string is not found in the main string.

E) T
S& FE
 The index() method returns ‘ValueError’ exception if the sub string is not found.
 The format of find() method is:
(C LS
 [Link](substring, beginning, ending)
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
A Python program to find the first occurrence of sub string in a given main
string.
 # to find first occurrence of sub string in a main string
str = input('Enter main string: ')
sub = input('Enter sub string: ')
# find position of sub in str
# search from 0th to last characters in str

h
n = [Link](sub, 0, len(str))

ec
if n == -1: # find() returns -1 if sub string is not found

.T
print('Sub string not found')

B
else:

E) T
print('Sub string found at position: ', n+1)

S& FE
 Output:
C:\>python [Link]
(C LS
Enter main string: This is GLS
G

Enter sub string: is


Sub string is found at position: 3

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
A Python program to find the first occurrence of sub string in a given main
string.

 observe that the Sub string position is displayed to be at ‘n+1’.


 Since find() method starts counting from 0th position and we count from 1st
position, we need to add 1 to the result given by find() method to get correct
position number.

h
 The same program can be rewritten using index() method. If the sub string is not

ec
found, index() method returns ‘ValueError’ exception, we have to handle the

.T
exception in our program

B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Counting Substrings in a String
 The method count() is available to count the number of occurrences of a sub
string in a main string. The format of this method is:
 [Link](substring)
 This returns an integer number that represents how many times the substring is
found in the main string.

h
 We can limit our search by specifying beginning and ending positions in the

ec
count() method so that the substring position is counted only in that range.

.T
B
 Hence, the other form of count() method is:[Link](substring, beg,

E) T
end)

S& FE
 For example, we want to search for substring ‘Delhi’ in the main string ‘New Delhi’
(C LS
to know how many times the substring appeared in the main string.
 str = 'Tejas Bhatt'
G

 n = [Link]('Bhatt')
 Output : 1
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

String
Counting Substrings in a String
 Suppose, we want to know how many times ‘e’ is repeated in the main string in
the range from 0th to 2nd characters, we can write:
 n = [Link]('e', 0, 3)
 print(n)
 Output: 1

h
ec
 If we search for ‘e’ in the main string starting from 0 th character to the end of the

.T
string, we can write:

B
 n = [Link]('a', 0, len(str))

E) T
S& FE
 print(n)
 Output: 2
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Replacing a String with another String
 The replace() method is useful to replace a sub string in a string with another sub
string.
 The format of using this method is: [Link](old, new)
 This will replace all the occurrences of ‘old’ sub string with ‘new’ sub string in the
main string. For example,

h
 str = 'That is a beautiful girl'

ec
.T
 s1 = 'girl'

B
 s2 = 'flower'

E) T
S& FE
 str1 = [Link](s1, s2)
 print(str)
(C LS
#That is a beautiful girl
G

 print(str1) #That is a beautiful flower

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Splitting and Joining Strings
 The split() method is used to brake a string into pieces. These pieces are returned
as a list. For example, to brake the string ‘str’ where a comma ( , ) is found, we can
write: [Link](‘,’)
 Observe the comma inside the parentheses. It is called separator that represents
where to separate or cut the string. Similarly, the separator will be a space if we
want to cut the string at spaces.

h
 In the following example, we are cutting the string ‘str’ wherever a comma is

ec
found. The resultant string is stored in ‘str1’ which is a list.

.T
 str = 'one,two,three,four'

B
E) T
 str1 = [Link](',')
 print(str1)
S& FE
(C LS
 The output : ['one', 'two', 'three', 'four']
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Splitting and Joining Strings
A Python program to accept and display a group of numbers.
# to accept a group of numbers and display them.
str = input('Enter numbers separated by space: ')
# cut the string where a space is found
lst = [Link](' ')

h
# display the numbers from the list

ec
for i in lst:

.T
print(i)

B
 Output:C:\>python [Link]

E) T
S& FE
Enter numbers separated by space: 10 20 30 40
(C LS
10
20
G

30
40
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

String
Splitting and Joining Strings
 When a group of strings are given, it is possible to join them all and make a single
string. For this purpose, we can use join() method as: [Link](str)
 where, the ‘separator’ represents the character to be used between the strings in
the output. ‘str’ represents a tuple or list of strings.
 In the following example, we are taking a tuple ‘str’ that contains 3 strings as:

h
 str = ('one', 'two', 'three')

ec
.T
 We want to join the three strings and form a single string. Also, we want to use

B
hyphen ( - ) between the three strings in the output.

E) T
 The join() method can be written as:
 str1 = "-".join(str) S& FE
(C LS
 print(str1) # the output string is str1.
G

 Output: one-two-three

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Changing Case of a String
 Python offers 4 methods that are useful to change the case of a string. They are
upper(), lower(), swapcase(), title().
 The upper() method is used to convert all the characters of a string into uppercase
or capital letters.
 The lower() method converts the string into lowercase or into small letters.
 The swapcase() method converts the capital letters into small letters and vice

h
ec
versa.

.T
 The title() method converts the string such that each word in the string will start

B
with a capital letter and remaining will be small letters. The following examples:

E) T
 str = 'Python is the future'
 print([Link]())
S& FE
(C LS
 print([Link]())
G

 print([Link]())
 print([Link]())

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

String
Changing Case of a String
 Python offers 4 methods that are useful to change the case of a string. They are
upper(), lower(), swapcase(), title().
 The upper() method is used to convert all the characters of a string into uppercase
or capital letters.
 The lower() method converts the string into lowercase or into small letters.
 The swapcase() method converts the capital letters into small letters and vice

h
ec
versa.

.T
 The title() method converts the string such that each word in the string will start

B
with a capital letter and remaining will be small letters. The following examples:

E) T
 str = 'Python is the future'
 print([Link]())
S& FE
(C LS
 print([Link]())
G

 print([Link]())
 print([Link]())

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )

You might also like