0% found this document useful (0 votes)
14 views16 pages

Students Notes

Uploaded by

Manjeet Yadav
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)
14 views16 pages

Students Notes

Uploaded by

Manjeet Yadav
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/ 16

String

String is a sequence which is made up of one or more characters. The character can be a
letter, digit, whitespace or any other symbol. A string can be created by enclosing one or
more characters in single, double or triple quote.
For example
>>>str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!'''
str1, str2, str3, str4 are all string variables having the same value 'Hello World!'.
Values stored in str3 and str4 can be extended to multiple lines using triple codes as can be
seen in the following example:
>>> str3 = """Hello World!
welcome to the world of Python"""
>>> str4 = '''Hello World!
welcome to the world of Python'''

String types in Python

There are two types :

1) Single line strings : A string that can be created by enclosing one or more characters in
single or double quotes are single line strings i.e. they must terminate in one line.
For example :
>>>str1 = 'Hello World!'
>>> str2 = "Hello World!"

2) Multiline strings text spread across multiple lines are multi line strings. Multiline strings
can be created in following two ways :
a) By adding a back slash at the end of a single or double quotes.
For example :
>>> a = 'computer\
science'
>>> a
'computerscience'
>>> len(a)
15

b) By typing the text in triple quotes marks (both single quotes or double quotes three times)

For example :
>>> a = '''computer
science'''
>>> a
'computer\nscience'
>>> len(a)
16

Page 1 of 16
Accessing Characters in a String

Each individual character in a string can be accessed using a technique called indexing. The
index specifies the character to be accessed in the string and is written in square brackets ([ ]).
The index of the first character (from left) in the string is 0 and the last character is n-1 where
n is the length of the string. If we give index value out of this range then we get an
IndexError. The index must be an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
The index can also be an expression including variables and operators but the expression
must evaluate to an integer.
#an expression resulting in an integer index
#so gives 6th character of str1
>>> str1[2+4]
'W'
#gives error as index must be an integer
>>> str1[1.5]
TypeError: string indices must be integers

Python allows an index value to be negative also. Negative indices are used when we want to
access the characters of the string from right to left. Starting from right hand side, the first
character has the index as -1 and the last character has the index –n where n is the length of
the string.

Indexing of characters in string 'Hello World!'

Positive Indices 0 1 2 3 4 5 6 7 8 9 10 11
String H e l L o W o r l d !
Negative -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Indices

String is Immutable

A string is an immutable data type. It means that the contents of the string cannot be changed
after it has been created. An attempt to do this would lead to an error.
>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a'

Page 2 of 16
>>> str1[1] = 'a'
TypeError: 'str' object does not support item assignment

String Operations

Concatenation : To concatenate means to join. Python allows us to join two strings using
concatenation operator plus which is denoted by symbol +.
e.g.
>>> s1 = 'class'
>>> s2 = 'xi d'
>>> s3 = s1 + s2
>>> s3
'classxi d'

NOTE : + operator is that operator that can work with numbers and strings separately for
addition and concatenation resp. but in the same expression you can not combine numbers
and strings as operands with + operator
For Example :
>>> 2+3
5
>>> '2'+'3'
'23'
>>> '2'+3
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
'2'+3
TypeError: can only concatenate str (not "int") to str

Replication : Python creates a new string that is number of repetitions of the input string using
repetition operator which is denoted by symbol *.
>>> s = 'hello'
>>> s * 5
'hellohellohellohellohello'

Note: str1 still remains the same after the use of repetition operator.
Note: * operator is that operator that can work with numbers as multiplication operator and
with a string and a number for replication respectively but in the same expression you can not
have strings as both the operands with * operator

For Example :
>>> 2*3
6
>>> '2'*3
'222'
>>> '2'*'3'
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
'2'*'3'
TypeError: can't multiply sequence by non-int of type 'str'

Page 3 of 16
Membership Operators
in : in is a binary operator which returns True if a character or a substring exists in the given
string; False otherwise
not in : not in is a binary operator which returns True if a character or a substring does not
exist in the given string; False otherwise

>>> s = 'hello'
>>> 'h' in s
True
>>> 'hh' in s
False
>>> 'h' not in s
False
>>> 'hh' not in s
True

String Slicing

Slicing is a method to access some part of string or substring which is 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, i.e.,
(m-n). 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
Negative indexes can also be used for slicing.
>>> str1 = 'Hello World!'
#gives substring starting from index 1 to 4
>>> str1[1:5]
'ello'
#gives substring starting from 7 to 9
>>> str1[7:10]
'orl'
#index that is too big is truncated down to the end of the string
>>> str1[3:20]
'lo World!'
#first index > second index results in an empty '' string
>>> str1[7:2]
''
#if the first index is not mentioned, the slice starts from index 0.
# gives substring from index 0 to 4
>>> str1[:5]
'Hello'
# 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[6:]
'World!'

Some more Examples:

Page 4 of 16
>>> str1[0:10:2]
'HloWr'
>>> str1[0:10:3]
'HlWl'

Negative indexes can also be used for slicing.


#characters at index -6,-5,-4,-3 and -2 are sliced
>>> str1[-6:-1]
'World'
# If we ignore both the indexes and give step size as -1
# str1 string is obtained in the reverse order
>>> str1[::-1]
'!dlroW olleH'

More examples on negative index slicing


>>> s
>>> 'hello class xi d hello hello'
>>> s[-1 : -4] # step value not given so default step is taken which is +1
>>> '' # start value > stop value so return is null string
>>> s[-4 : -1 ]
>>> 'ell'
>>> s[-4 : -1 :-1 ] # if step value is -1 then start value > stop value
>>> '' # with step value -1 start value -4 < stop value -1 so result is null string
>>> s[-4 : -1 :1 ]
>>> 'ell'
>>> s[-1 : -4 :-1 ]
>>> 'oll'

TRAVERSING A STRING

Traversing refers to iterating through the elements of a string, one character at a time. There are
two ways to traverse a string
1. Using for loop
# traversal of a string using for loop

s ='Hello World'
for i in s :
print(i)

2. Using index value


# traversal of a string using index

s = 'Hello World'
l = len(s)
for i in range(l) :
print(s[i])

Page 5 of 16
STRING METHODS

len() : Returns the length of the string.


>>> s = 'computer science'
>>> l = len(s)
>>> l
16

capitalize() : returns the exact copy of the string with only the first letter in upper case
and other letters in lower case
>>> s = 'computer science'
>>> s1 = s.capitalize()
>>> s1
'Computer science'
>>> s = 'computer Science'
>>> s1 = s.capitalize()
>>> s1
'Computer science'
>>> s = 'Computer science'
>>> s1 = s.capitalize()
>>> s1
'Computer science'
>>> s='12345'
>>> s1 = s.capitalize()
>>> s1
'12345'
>>> s='a12345'
>>> s1 = s.capitalize()
>>> s1
'A12345'

count(str,[ start[, end]]) : Returns number of times substring str occurs in the given string. If
we do not give start index and end index then searching starts from index 0 and ends at length
of the string. If end is given then value is excluded which means search will be till end -1.

>>> s = 'Hello World! Hello Hello'


>>> s.count('hello')
0
>>> s.count('Hello')
3
>>> s.count('Hello', 10)
2
>>> s.count('Hello', 10, 18)
1
>>> s.count('Hello',0, 4)
0 # as end given as 4 so search is till index number 3.
>>> s.count('Hel',-5,-1)
1
>>> s.count('Hel',-5,-3)
0

Page 6 of 16
>>> s.count('Hel',-1,-5)
0
>>> s.count('Hel',0, -6)
2

find(sub [,start[,end]]) : the function is used to search the first occurrence of the substring in
the given string. It returns the index at which the substring starts. It returns -1 if the substring
does not occur in the string.
Parameter values

value Required. The value to search for

start Optional. Where to start the search. Default is 0

end Optional. Where to end the search. Default is to the end of the string it searches till
end-1 index number

NOTE : if the index number for start and stop is negative and if the substring is found within
the given range of negative index the output will be positive index number
NOTE : if start index is negative and not in range of string then it search from index number
0 but same is not valid for positive start index number means if start index is positive and not
present in the given string from where we need to search the substring then -1 is returned.

>>> s = "Hello welcome to my world"


>>> x = s.find('el')
>>> x
1
>>> x = s.find('el', 5)
>>> x
7
>>> x = s.find('el', 8)
>>> x
-1
>>> x = s.find('el', 2,8)
>>> x
-1
>>> x = s.find('el', 2,9)
>>> x
7
>>> x=s.find('el', -18, -3) # start and stop is negative and substring is found within the given
# range of negative index the output is positive index number
>>> x
7
>>> x=s.find('el', -3, -18)
>>> x
-1
>>> x=s.find('el', -17, -3)
>>> x
-1

Page 7 of 16
>>> x=s.find('el', -36, -3) # start index is negative and not in range of string, search from
# index number 0
>>> x
1
>>> x=s.find('el', -36, 1)
>>> x
-1
>>> x=s.find('el', 34) # start index is positive and not present in the given string from where
# we need to search the substring , -1 is returned.
>>> x
-1

More examples :

Assume the following string s

>>> s='Hello, welcome to my world. Hello'

>>> s.find('Hello', 1)
28
>>> s.find('Hello', 1, 10)
-1
>>> s.find('Hello', 1, 90)
28
>>> s.find('Hello', 90)
-1
>>> s.find('Hello', 30)
-1

index(str[, start[, end]]) : Same as find() but raises an exception if the substring is not
present in the given string
>>> s = 'Hello World! Hello Hello'
>>> s.index('Hello')
0
>>> s.index('Hello', 3)
13
>>> s.index('Hello', 3, 10)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
s.index('Hello', 3, 10)
ValueError: substring not found
>>> s.index('Hi')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
s.index('Hi')
ValueError: substring not found

Page 8 of 16
isalnum() : checks whether all the characters in a given string is alphanumeric(A character
that is either a letter or a number) or not. It takes no parameter and returns True if all the
characters are alphanumeric else returns False.
>>> s = "Hello, welcome to my world."
>>> a = s.isalnum()
>>> a
False
>>> s='a12345'
>>> a = s.isalnum()
>>> a
True

isalpha() : checks whether all the characters in a given string is alphabet or not. It takes no
parameter and returns True if all the characters are alphabets only else returns False
>>> 'ABC123'.isalpha()
False
>>> 'ABC 123'.isalpha()
False
>>> 'ABC abc'.isalpha()
False # contains space in the string so answer is False
>>> 'ABCabc'.isalpha()
True

isupper() : it checks and returns True if given string has any one upper case alphabet (A-Z)
and no lower case alphabet
NOTE : characters other than alphabets do not change the answer if present in the given
string.

Example :

>>> '123'.isupper()
False
>>> 'ABC123'.isupper()
True
>>> 'ABc123'.isupper()
False
>>> 'ABC CBA'.isupper()
True

islower( ) : it checks and returns True if given string has any one lower case alphabet (a-z)
and no upper case alphabet
NOTE : characters other than alphabets do not change the answer if present in the given
string.

>>> '123'.islower()
False
>>> 'abc123'.islower()
True
>>> 'Abc123'.islower()
False

Page 9 of 16
>>> s = 'abc aba'
>>> s.islower()
True

More examples

>>> s = 'abs +++'


>>> s.islower()
True
>>> s = 'abs F++'
>>> s.islower()
False

isdigit() : it checks and returns True if given string has only digits else returns False.
>>> '123'.isdigit()
True
>>> '123abc'.isdigit()
False
>>> 'ab123'.isdigit()
False

>>>s = '123 451'


>>>s.isdigit() # s contains space so answer is false
False

isspace() :returns true if string contains whitespaces characters otherwise returns False.

>>> s = 'welcome'
>>> s.isspace()
False
>>> s = ' asd'
>>> s.isspace()
False
>>> s = ' '
>>> s.isspace()
True

lower() : returns the exact copy of the string with all the letters in lowercase, It takes no
parameter.
>>> s = 'Computer sciENCE123'
>>> s = s.lower()
>>> s
'computer science123'
>>> s = 'Hello'.lower()
>>> s
'hello'

Page 10 of 16
upper() : returns the exact copy of the string with all the letters in uppercase, it takes no
parameter

>>> s = 'Computer sciENCE123'

>>> x=s.upper() # converts and returns string in upper case.


>>> x
'COMPUTER SCIENCE123'

Note to remember :
>>> s # there is no change in original string
'Computer sciENCE123'

>>> s='hello'.upper()
>>> s
'HELLO'

lstrip([characters]) : The lstrip() method returns a copy of the string with leading characters
removed (based on the string argument passed). The lstrip() removes characters from the left
based on the argument (a string specifying the set of characters to be removed)
It takes an optional string parameter which specifies the set of characters to be removed. (It
removes any combination of specified string from the given string if available on left side of
the given string) If the characters argument is not specified, all leading whitespaces are
removed from the string.
>>> s = 'welcome'
>>> s.lstrip('wl')
'elcome'
>>> s = 'welcome'
>>> s.lstrip('lwe')
'come'
>>> s = ",,,,,ssaaww.....banana"
>>> x = s.lstrip(',asw.')
>>> x
'banana'
>>> s = ",,,,,ssaaww.....banana"
>>> x = s.lstrip(',asw')
>>> x
'.....banana'
>>> s = ",,,,,ssaaww.....banana"
>>> x = s.lstrip()
>>> x
',,,,,ssaaww.....banana'
>>> s = ' compter science '
>>> x = s.lstrip()
>>> x
'compter science '

Page 11 of 16
rstrip() : same as lstrip(), from right side

strip([characters]) : strip() is an inbuilt function in Python programming language that


returns a copy of the string with both leading and trailing characters removed (based on the
string argument passed).

title() : Returns the string with first letter of every word in the string in uppercase and rest in
lowercase
If the word contains a number or a symbol, the first letter after that will be converted to upper
case.
>>> s = 'computer science'
>>> t = s.title()
>>> t
'Computer Science'
>>> s = 'Computer science'
>>> t = s.title()
>>> t
'Computer Science'
>>> s = '123 678'
>>> t = s.title()
>>> t
'123 678'
>>> s = '123abs per234'
>>> t = s.title()
>>> t
'123Abs Per234'

istitle( ) : returns True if the string is title cased (first character of every word capital)
otherwise returns False
>>> str = 'Computer scince class'
>>> str.istitle()
False
>>> s2= 'Computer Science Class'
>>> s2.istitle()
True
>>> s2= 'Computer Science Class'
>>> a =s2.istitle()
>>> a
True

replace() : the function replaces all the occurrences of the old string with the new one

>>> str = 'hello'


>>> str = 'Sunday Monday Tuesday Wednesday'
>>> str.replace(' ' ,'-')
'Sunday-Monday-Tuesday-Wednesday'
>>> str
'Sunday Monday Tuesday Wednesday'
>>> str = str.replace(' ' ,'-')
>>> str

Page 12 of 16
'Sunday-Monday-Tuesday-Wednesday'

join() : returns a string in which the sequence (list, tuple, string) have been joined by a
separator.
NOTE : function called by string to be joined in the given sequence which is passed as
parameter.

Tuple example

>>> t = ('Sunday', 'Monday', 'Tuesday','Wednesday')


>>> s = '&'
>>> s.join(t)
'Sunday&Monday&Tuesday&Wednesday'

String example : characters in the string have been joined by a separator

>>> s = 'Honest'
>>> p = '-'
>>> p.join(s)
'H-o-n-e-s-t'

More examples
>>> s = 'hello'
>>> p='-'
>>> s.join(p)
>>> '-'
>>> p.join(s)
>>> 'h-e-l-l-o'
>>> p = '--'
>>> s.join(p)
>>> '-hello-'

List example :

>>> L = ['Sunday', 'Monday', 'Tuesday','Wednesday']


>>> s = '$$'
>>> s.join(L)
'Sunday$$Monday$$Tuesday$$Wednesday'

swapcase() : returns the string with case changes.


>>> s = 'CompuTER ScienCE'
>>> s1 = s.swapcase()
>>> s1
'cOMPUter sCIENce'
>>> s = '133 Model Town'
>>> s1 = s.swapcase()
>>> s1
'133 mODEL tOWN'

Page 13 of 16
endswith( ) : Returns True if the given string ends with the supplied substring otherwise
returns False
The endswith() takes three parameters:

• Substring - String to be checked


• start (optional) - Beginning position where suffix is to be checked within the string.
• end (optional) - Ending position where suffix is to be checked within the string. If end is
given then value is excluded which means search will be till end -1

>>> s = 'Hello World!'


>>> a = s.endswith('WORLd!')
>>> a
False
>>> a = s.endswith('World!')
>>> a
True
>>> a = s.endswith()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a = s.endswith()
TypeError: endswith() takes at least 1 argument (0 given)
>>> s.endswith('World!', 8)
False
>>> s.endswith('World!', 0, 7)
False

startswith( ) : Returns True if the given string starts with the supplied substring otherwise
returns False
The startswith() method takes maximum of three parameters:

• prefix - String or tuple of strings to be checked


• start (optional) - Beginning position where prefix is to be checked within the string.
• end (optional) - Ending position where prefix is to be checked within the string. If end is given then value is
excluded which means search will be till end -1

>>> s = 'All the best'


*>>> s.startswith('best')
False
>>> s.startswith('All')
True
>>> s.startswith('All', 2)
False
>>> s.startswith('All', 2,7)
False
>>> s.startswith('All', 0,7)
True
>>> s.startswith('All', 1,7)
False

Page 14 of 16
partition( ) : Partitions the given string at the first occurrence of the substring (separator) and
returns the string partitioned into three parts in a tuple. 1. Substring before the separator 2.
Separator 3. Substring after the separator If the separator is not found in the string, it returns
the whole string itself and two empty strings

Parameter Description

Value Required. The string to search for

>>> a = "An apple a day keeps the doctor away"


>>> a.partition('a')
('An ', 'a', 'pple a day keeps the doctor away')
>>> a = "An apple a day keeps the doctor away"
>>> a.partition('apple')
('An ', 'apple', ' a day keeps the doctor away')
>>> a.partition('mango')
('An apple a day keeps the doctor away', '', '')

split([sep[,maxsplit]]) : Returns a list of words delimited by the specified substring. (i.e after
splitting the string into substrings using the separators) If no delimiter is given then words are
separated by space.

Parameter Values
Parameter Description

Separator Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator

Maxsplit Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"

>>> s = 'I Love Python Programming Language'


>>> s.split()
['I', 'Love', 'Python', 'Programming', 'Language']
>>> s.split('a')
['I Love Python Progr', 'mming L', 'ngu', 'ge']
>>> s.split('a', 2)
['I Love Python Progr', 'mming L', 'nguage']
>>> s.split('a', 1)
['I Love Python Progr', 'mming Language']
>>> s.split(' ', 1)
['I', 'Love Python Programming Language']
>>> s.split(1)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
s.split(1)
TypeError: must be str or None, not int
Page 15 of 16
ord() : This function returns the ASCII (American Standard Code for Information
Interchange) of the character .
For example
>>> ord('A')
65
>>> ord('a')
97
>>> ord('d')
100
>>> ord('D')
68

chr() : This function returns the character represented by the inputted ASCII number.
>>> chr(65)
'A'
>>> chr(97)
'a'
>>> chr(66)
'B'
>>> chr(100)
'd'

Page 16 of 16

You might also like