Unit-3 Part-I
Unit-3 Part-I
Unit-3 Part-I
STRINGS
STRINGS : Accessing Characters and Substrings in a String, String Methods, Basic String
operations, String Slicing, Testing, Searching, Comparing and manipulating Strings.
STRINGS:
A string can be either created by using single quotes (' ') or double quotes(" "). Python treats
single quotes the same as double quotes.
A string can be created using either single quotes or double quotes .However,if your string
contains double quotes use single quotes. And if your string contains single quotes use double
quotes.
example :
1)
Output:
2)
Output:
str='Hii everyone!"Welcome to python" ' # if your string contains double quotes use single
quotes
Output:
str="Hii everyone!'Welcome to python' " # if your string contains single quotes use double
quotes
Output:
Multiline strings
To create a multiline string,surround or enclose a string with triple single quotes(''' ''')or triple
double quotes(""" """).
Example :
str='''hii
hello
world'''
hii
hello
world
In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references too to access characters from the back of the String,
e.g. -1 refers to the last character, -2 refers to the second last character and so on. This negative
indexing is called as backward indexing. The positive indexing is called as forward
indexing,example 0 represents the first character , 1 represents the second character, 2 represents
the third chaqrcter and so on.
Indexing
0 represents the first character , 1 represents the second character of a string and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed
to be passed as an index, float or other types will cause a TypeError.
Example :
1) #forward indexing
str="hi everyone"
print(str[0]) # prints h
print(str[1]) # prints i
Output:
while -1 represents the last character,and -2 represents the second to the last character .
2) #backward indexing
str="hi everyone"
print(str[-1]) # prints e
print(str[-2]) # prints n
Output:
STRING METHODS
Python has a set of built-in methods that you can use on strings.
Ex:
Note: All string methods returns new values. They do not change the original string.
1) Capitalize String
The capitalize() function returns the string where the first letter is in uppercase.
Example
Output:
2) Upper() function
Convert to upper case
The upper() function returns a copy of the given string but all the letters are in upper case.
Example
# upper() function
x=str.upper()
Output:
3) Lower() function
Convert to lower case
The lower() function returns a copy of the given string but all letters are in lower case.
Example
1)
# lower() function
str='HI EVERYONE!WELCOE TO PYTHON'
x=str.lower()
print(str) # the string remains the same
print(x) # the sting converts into lower case
Output:
HI EVERYONE!WELCOE TO PYTHON
hieveryone!welcoe to python
2)
# lower() function
str='Hi Everyone!Welcome To Python'
x=str.lower()
print(str) # the string remains the same
print(x) # the sting converts into lower case
Output:
Hi Everyone!Welcome To Python
hieveryone!welcome to python
4) len() function
Get the length of the string.
The length of a string is the number of characters it contains.
The len() function returns the length of a string.
It takes one parameter,the string.
Example
1)
#length of the string
str='Hi Everyone!Welcome To Python'
print(len(str))
output:
29
2)
#length of the string
str='Hi Everyone!Welcome To Python'
x=len(str)
print("the length of the string is ",x)
Output:
the length of the string is 29
5) replace() function
Replacing parts of the string
The replace() function replaces the occurrences of a specified substring with another substring.
Syntax:
string.replace(old,new)
1)
#replace() function
str="Hello World!"
x=str.replace("World","Everyone")
Output:
Hello World!
Hello Everyone!
2) Now , in this example world will not be replaced with Everyone because the first letter of the
world is not in upper case , to replace the old substring with new substring the first letter of
the old substring should be in uppercase i.e World.
Example
#replace() function
str="Hello World!"
x=str.replace("world","Everyone")
print(x) #the first letter of the old substring is not in upper case
Output:
Hello World!
Hello World!
3) The replace() function replaces all occurences of the old substring with the new substring.
Example
x=str.replace("World","Everyone")
print(x)
Output:
4)
But you can specify how many occurences you would like to be replaced, on the third argument.
In this example,onlytwo occurences of the substring World will be replaced with Everyone.
Example
#replace() function replaces all occurences of the old substring with the new substring
x=str.replace("World","Everyone",2)
print(str)
print(x)
Output:
Hello World! I Love World! World is amazing!
Example:
str="python is fun to learn"
x="learn" in str
print(x)
Output:
True
● Alternatively, you can use the not inkeyword ,it returns True if the substring is not
found .
Example :
str="python is fun to learn"
x="world" not in str #it returns true if the substring is not found in the string
print(x)
Output:
True
7) find() Method
*The find() method finds the first occurrence of the specified value.
*The find() method is almost the same as the index() method, the only difference is that 2)
# The find() method finds the first occurrence of the specified value
x=str.find("Hello")
print(x)
Output:
x=str.find("Hi")
print(x)
Output:
-1
8) count() method
The count() method returns the number of times a specified value appears in the string.
#count() method
x=str.count("python")
print(x)
Output:
3
9) index() Method
#index() method
1)
x=str.index("welcome")
print(x)
Output:
2)
x =txt.index("e")
print(x)
Output:
10)isalpha() Method
The isalpha() method returns True if all the characters are alphabet letters (a-z).
1)
#isaplpha() method
str="hiiipython"
x=str.isalpha()
print(x)
Output:
True
2)
#isaplpha() method
str="hiii python"
x=str.isalpha()
print(x)
Output:
False
3)
#isaplpha() method
str="hiii python3@2020"
x=str.isalpha()
print(x)
Output:
False
11)
isdigit() Method
The isdigit() method returns True if all the characters are digits, otherwise False.
Example:
#isdigit() method
str="59111321"
x=str.isdigit()
print(x) # True
Output:
True
The title() method returns a string where the first character in every word is upper case. Like
a header, or a title.
If the word contains a number or a symbol, the first letter after that will be converted to upper
case.
#title() method
x=str.title()
Output:
13)swapcase() Method
The swapcase() method returns a string where all the upper case letters are lower case and vice
versa.
Example:
1)
#swapcase() method
str="Hiii Python"
x=str.swapcase()
print(x)
Output:
hIIIpYTHON
2)
#swapcase() method
str="Hello World"
x=str.swapcase()
print(x)
Output:
hELLOwORLD
These are some string methods in detail.There are many string methods or string functions and
they are as follows
Note: All string methods returns new values. They do not change the original string.
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was found
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
In python, String operators represent the different types of operations that can be employed on
the program’s string type of variables. Python allows several string operators that can be applied
on the python string are as below:
● Assignment operator(=)
● Concatenate operator(+)
● String repetition operator(*)
● String slicing operator([])
● String comparison operator(“==” & “!=”)
● Membership operator(“in”& “not in”)
● Escape sequence operator( \)
● String formatting operator(“%” & “{}”)
1)Assignment operator(=)
Python string can be assigned to any variable with an assignment operator “= “. Python string
can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’ ‘’’].
var_name = “string” assigns “string” to variable var_name.
syntax:
varaiblename="string"
Example:
Output:
Two strings can be concatenated or join using the “+” operator in python.
Concatenating strings simply means combining or adding strings together. We can combine as
many as strings we want.
Example:
str1="hii everyone!"
print(str)
Output:
Example:
#String repetition operator (*)
str="Python is amazing!"
print(str*5)
Output:
amazing!
#slicing str[startindex:endindex]
str="Hi Everyone"
print(str[0:5]) # prints Hi Ev
Output:
Hi Everyon
● “==” operator returns Boolean True if two strings are the same and return Boolean False
if two strings are not the same.
● “!=” operator returns Boolean True if two strings are not the same and return Boolean
False if two strings are the same.
These operators are mainly used along with if condition to compare two strings where the
Example:
In The in Operator
not in The not in Operator
The in Operator
The in operator returns True if a sequence or value is present in an object.
Example:
1) This example prints True because the sequence "python" is present in the str variable.
x="python" in str
print(x)
Output:
True
2) This example prints False because the sequence "hii" is not present in the str variable.
x="hii" in str
print(x)
Output:
False
Example:
1. This example prints True because the sequence “vegetables” is NOT present in the string
variable .
#the not in operator
print(x)
Output:
True
2)
This example prints False because the sequence “fruits” is NOT present in the string variable .
print(x)
Output:
False
print(str)
Output:
Invalid Syntax error
print(str)
Output:
let's learn Python
String formatting operator is used to format a string as per requirement. To insert another type of
variable along with string, the “%” operator is used along with python string. “%” is prefixed to
another character indicating the type of value we want to insert along with the python string.
Please refer to the below table for some of the commonly used different string formatting
specifiers:
Operator Description
%c Character
%s String
Example:
name="Python"
year=1991
print(str1)
print(str2)
print(str3)
Output:
Method-2
Placeholders { }
In this example, we will concatenate (add) a substring to where the curly braces are placed.
str=x.format("Python")
STRING SLICING
To access a range of characters,usesilicing. Slicing uses square brackets( [] ).
The square brackets can contain two integers separated by a colon( : ). The first integer is the
a. str(startindex:stopindex)
It prints the startindex value to the stopindexvalue excluding the stopindex element.
b. str(startindex:)
If we donot mention the stopindex value then it prints the value form startindex to the end
c. str(:stopindex)
If we donot mention the start index value then it prints the value form startindex of the
d. str(:)
If we donot mention the start index and stop index then it prints the string as the same as
Example
1)str(startindex:stopindex)
It prints the startindex value to the stopindex value excluding the stopindex element.
#slicingstr[startindex:endindex]
str="Hi Everyone"
print(str[0:5]) # prints Hi Ev
Output:
Hi Ev
2)str(startindex:)
If we donot mention the stopindex value then it prints the value form startindex to the end
of the string(including the last element ).
#slicing str[startindex:]
str="Hi Everyone"
Output:
Everyone
3) str(:stopindex)
If we donot mention the start index value then it prints the value form startindex of the
string to the end of the stopindex (excluding the stopindexelement ).
#slicing str[:stopindex]
str="Hi Everyone"
Output:
Hi Everyon
4)str(:)
If we donot mention the start index and stop index then it prints the string as the same as
the original string.
#slicing str[:]
str="Hi Everyone"
Output:
Hi Everyone
The relational operators compare the Unicode values of the characters of the strings from the
zeroth index till the end of the string. It then returns a boolean value according to the operator
used.
Example:
print("AIML" == "AIML")
print("Aiml" != "Aiml")
Output:
True
True
False
False
str1 = "CMR"
str2 = "CMR"
str3 = str1
str1 += "IT"
str4 = "CMRIT"
Output:
ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True
True
The object ID of the strings may vary on different machines. The object IDs of str1, str2 and str3
were the same therefore they the result is True in all the cases. After the object id of str1 is
changed, the result of str1 and str2 will be false. Even after creating str4 with the same contents
as in the new str1, the answer will be false as their object IDs are different.
Vice-versa will happen with is not.
TESTING STRINGS
String class in python has various inbuilt methods which allows to check for different types of
strings.
Example:
find(s1): int Returns lowest index from where s1 starts in the string, if string not found
returns -1
rfind(s1): int Returns highest index from where s1 starts in the string, if string not found
returns -1