2. Contents..
Strings and Operations-
• Python Strings
• Concatenating, Appending and Multiplying strings
• Strings are immutable
• strings formatting operator
• Built in string methods and functions.
• Slice operation
• ord() and chr() functions
• in and not in operators
• comparing strings
• Iterating strings
• String module
2
3. Strings
• A string is a sequence of characters.
• A character could be letter, digit, whitespace or any other
symbol.
• Strings in python are surrounded by either single quotation
marks, or double quotation marks.
– 'hello' is the same as "hello".
• Even triple quotes can be used in Python but generally used to
represent multiline strings and docstrings.
• String variables:
– name=“India”
– country=name
– graduate=‘Y’
– nationality=str(“Indian”)
3
4. Strings
• # defining strings in Python
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
Hello
Hello
Hello, welcome to
the world of Python
4
5. Strings
• Str() function is used to convert values of any other type into string type.
• Example:
mystr = "Roll No : "
roll = 15
stud_roll_no = mystr + roll
print(stud_roll_no)
• Example:
mystr = "Roll No : "
roll = 15
stud_roll_no = mystr + str(roll)
print(stud_roll_no)
5
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/P1/main.py", line 3,
in <module>
stud_roll_no = mystr + roll
TypeError: can only concatenate str (not "int") to str
Roll No : 15
6. Strings
• String Indexing:
• An individual character in a string can be accessed using subscript [ ]
operator.
• Index of first character is 0 and that of last character is (n-1).
• If you try to exceed the bounds (below 0 or above n -1) then an error is
raised.
• Ttraversing a string:
• String can be traversed by accessing characters from one index to
another.
• Example:
message = "Hello"
index=0
for i in message:
print("message [", index, "]=",i)
index+=1
6
message [ 0 ]= H
message [ 1 ]= e
message [ 2 ]= l
message [ 3 ]= l
message [ 4 ]= o
7. Concatenating strings
• Concatenate means to join together .
• Python allows to concatenate 2 strings using + operator.
• Example:
str1 = "Hello"
str2 = "World"
str3 = str1 + str2
print("Concatenated string is : ",str3)
7
Concatenated string is : HelloWorld
8. Appending strings
• Append mean to add something at the end .
• Python allows to add one string at the end of another string using +=
operator.
• Example:
str = "Hello, "
name = input("Enter your name : ")
str+= name
str+= "! nWelcome to BVCOEL Pune"
print(str)
8
Enter your name : Prajakta
Hello, Prajakta!
Welcome to BVCOEL Pune
9. Multiplying strings
• You can use * operator to repeat a string in number of times
• Example:
str = "Hello! "
print(str * 3)
9
Hello! Hello! Hello!
10. String slicing
• Substring of a string is called a slice .
• Slice operation is used to refer to subparts of sequences or string .
• It can be done using slicing operator [ ].
• Indices in a string :
P Y T H O N
0 1 2 3 4 5 (Index from start)
-6 -5 -4 -3 -2 -1 (index from end )
• Syntax of slice operation : S[start :end ]
• In Slice operation you can specify third argument as the stride which
refers to the number of characters to move forward after the first
character is retrieved from the string .
• S[start : end : stride]
• Default value for stride is 1 .
10
11. String slicing
• Example :
#Accessing string characters in Python
mystr = 'BVCOELPune'
print('mystr = ', mystr)
#first character
print('mystr[0] = ', mystr[0])
#last character
print('mystr[-1] = ', mystr[-1])
#slicing 2nd to 5th character
print('mystr[1:5] = ', mystr[1:5])
#slicing 6th to 2nd last character
print('mystr[5:-2] = ', mystr[5:-2])
11
mystr = BVCOELPune
mystr[0] = B
mystr[-1] = e
mystr[1:5] = VCOE
mystr[5:-2] = LPu
12. String slicing
• Example :
mystr = 'Welcome to BVCOEL'
print('mystr = ', mystr)
#Default stride is 1
print('mystr[2:10] = ', mystr[2:10])
#same as stride equal to 1
print('mystr[2:10:1] = ', mystr[2:10:1])
#skips every alternate character
print('mystr[0: :2] = ', mystr[0: :2])
#skips every 4th character
print('mystr[0: :4] = ', mystr[0: :4])
#Splice operation
print('mystr[ : : 3] = ', mystr[ : : 3])
12
mystr = Welcome to BVCOEL
mystr[2:10] = lcome to
mystr[2:10:1] = lcome to
mystr[0: :2] = Wloet VOL
mystr[0: :4] = WotVL
mystr[ : : 3] = WceoVE
13. Strings are immutable
• Strings are immutable.
• This means that elements of a string cannot be changed once they have
been assigned. We can simply reassign different strings to the same
name.
• Example:
str1 = "Python 2"
str1[7]=3
print(str1)
• We cannot delete or remove characters from a string but we can delete
entire string using keyword del.
13
Traceback (most recent call last):
File "C:/Users/admin/PycharmProjects/p1/main.py", line 2, in <module>
str1[7]=3
TypeError: 'str' object does not support item assignment
14. strings formatting operator
• Python uses C-style string formatting to create new, formatted strings.
• The "%" operator is used to format a set of variables enclosed in a
"tuple" (a fixed size list), together with a format string.
• Format string contains normal text together with "argument specifiers",
special symbols like "%s" and "%d".
• Argument specifiers:
• %d or %i – signed decimal integer
• %f – floating point number
• %s – string
• %x or %X– hexadecimal integer
• %o – octal integer
• %c – character
• %u – unsigned decimal integer
• %.<number of digits>f – Floating point numbers with a fixed amount of digits
to the right of the dot.
14
15. strings formatting operator
• Example:
# Initialize variable as a string
variable = '15'
string = "Variable as string = %s" % (variable)
print(string)
# Printing as raw data
print("Variable as raw data = %r" % (variable))
# Convert the variable to integer
variable = int(variable)
string = "Variable as integer = %d" % (variable)
print(string)
print("Variable as float = %f" % (variable))
print("Variable as hexadecimal = %x" % (variable))
print("Variable as octal = %o" % (variable))
15
Variable as string = 15
Variable as raw data = '15'
Variable as integer = 15
Variable as float = 15.000000
Variable as hexadecimal = f
Variable as octal = 17
16. strings formatting
• Using format
• In this approach we use the in-built function called format.
• We use {} for placeholders of values that will be supplied by format.
• By default the positions will be filled in the same sequence of values
coming from format function.
• But we can also force the values in terms of positions starting with 0 as
index.
• Example:
weather = ['sunny','rainy']
day = ['Mon','Tue','Thu']
print('on {} it will be {}'.format(day[0], weather[1]))
print('on {} it will be {}'.format(day[1], weather[0]))
print('on {} it will be {}'.format(day[2], weather[1]))
# Using positions
print('on {0} it will be {1}'.format(day[0], weather[0]))
print('It will be {1} on {0}'.format(day[2], weather[1]))
16
on Mon it will be rainy
on Tue it will be sunny
on Thu it will be rainy
on Mon it will be sunny
It will be rainy on Thu
17. chr() function
• Python's built-in function chr() is used for converting an Integer to a Character.
• The chr() method returns a string representing a character whose Unicode code
point is an integer.
• The chr() method takes only one integer as argument.
• Syntax:
chr(num)
where num is integer value
• Example:
var=65
print(chr(var))
• Example:
print(chr(80))
print(chr(89))
print(chr(84))
print(chr(72))
print(chr(79))
print(chr(78))
17
A
P
Y
T
H
O
N
18. ord() function
• Function ord() is used to do the reverse of chr() function, convert a Character
to an Integer.
• The ord() function accepts a string of unit length as an argument and returns
the Unicode equivalence of the passed argument.
• ord() function returns the number representing the unicode code of a specified
character.
• Syntax:
ord("string")
• Example:
print(ord('a'))
• Example:
print(ord("P"))
print(ord("Y"))
print(ord("T"))
print(ord("H"))
print(ord("O"))
print(ord("N"))
18
97
80
89
84
72
79
78
19. in and not in operators
• Membership operators are operators used to validate the membership of a
value.
• It test for membership in a sequence, such as strings, lists, or tuples.
• in operator :
The 'in' operator is used to check if a value exists in a sequence or not.
Evaluates to true if it finds a variable in the specified sequence and
false otherwise.
'not in' operator :
Evaluates to true if it does not finds a variable in the specified sequence
and false otherwise.
• in and not in operators can be used with strings to determine whether a
string is present in another string.
19
20. in and not in operators
• Example:
mystr="Welcome to BVCOEL"
s1="come"
if s1 in mystr:
print("Found!!")
else:
print("Not Found!")
• Example:
mystr="Welcome to BVCOEL"
s1="Pune"
if s1 not in mystr:
print("Not Found!")
else:
print("Found!!")
20
Found!!
Not Found!
21. Comparing strings
• To compare two strings, we mean that we want to identify whether the
two strings are equivalent to each other or not, or perhaps which string
should be greater or smaller than the other.
• This is done using the following operators:
= =
This checks whether two strings are equal
!=
This checks if two strings are not equal
<
This checks if the string on its left is smaller than that on its right
<=
This checks if the string on its left is smaller than or equal to that on its right
>
This checks if the string on its left is greater than that on its right
> =
This checks if the string on its left is greater than or equal to that on its right
21
22. comparing strings
• These operators compare the strings by using the lexicographical order.
• The ASCII values of A-Z is 65 to 90 .
• The ASCII values of a-z 97 to 122 .
• Example :
‘book’ is greater than ‘Book’ because ASCII value of ‘b’ is 98
and ‘B’ is 66.
• Example:
print(("RED"=="RED"))
print(("RED"!="red"))
print(("abc">"Abc"))
print(("Main"<"main"))
print(("ABc"<="ABc"))
print(("aBC">="ABC"))
22
True
True
True
True
True
True
23. Iterating strings
• As string is a sequence of characters, we can iterate through the string
using loop structures such as for loop or while loop .
• Example 1:
s1="Welcome to BVCOEL"
for i in s1:
print(i,end=' ')
• Example 2:
s1="Welcome to BVCOEL"
i=0
while i < len(s1):
print(s1[i], end=" ")
i=i+1
23
W e l c o m e t o B V C O E L
W e l c o m e t o B V C O E L
24. Iterating strings
• We can iterate through a string either using index or by using each
character in the string.
• Example 1: Use character to iterate
def copy_str(s):
new_str=""
for i in s:
new_str+=i
return new_str
my_str="Welcome to BVCOEL"
print("Copied string is : ",copy_str(my_str))
24
Copied string is : Welcome to BVCOEL
25. Iterating strings
• Example 2: Use index of character to iterate
def copy_str(s):
new_str=""
for i in range(len(s)):
new_str+=s[i]
return new_str
my_str="Welcome to BVCOEL"
print("Copied string is : ",copy_str(my_str))
25
Copied string is : Welcome to BVCOEL
26. Built in string methods and functions
• Python has a set of built-in methods that you can use on strings.
• Strings are example of Python objects and object contains both data as
well as functions to manipulate that data.
• Python also supports many built-in methods to manipulate strings.
• Method is just like function, the only difference between a function and
method is that a method is invoked or called on an object.
• Method is called by its name, but it is associated to an object
(dependent) .
• A method is implicitly passed the object on which it is invoked.
• Function is block of code that is also called by its name. (independent).
• The function can have different parameters or may not have any at all.
If any data (parameters) are passed, they are passed explicitly.
26
27. Python String Methods
27
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
title() Returns a string with first letter of each word capitalized; a title cased string.
swapcase() converts all uppercase characters to lowercase and all lowercase characters to
uppercase characters of the given string and returns it.
count() Returns the number of times a specified value occurs in a string
endswith() Checks if String Ends with the Specified Suffix
startswith() Checks if String Starts with the Specified String
upper() Returns uppercased string
lower() Returns lowercased string
find() Searches the string for a specified value & returns the position of where it was found
(Returns -1 if not found)
rfind() Searches the string for a specified value & returns the last position of where it was
found (Returns -1 if not found)
28. Python String Methods
28
Method Description
index() Searches the string for a specified value and returns the position of where it was
found (Raises an exception if not found)
rindex() Searches the string for a specified value and returns the last position of where it was
found (Raises an exception if not found)
format() Formats the given string into a nicer output and returns the formatted string.
join() Returns a Concatenated String.
split() Splits String from Left and returns a list of strings.
strip() Returns a copy of the string by removing both the leading and the trailing characters.
replace() Replaces each matching occurrence of the old character/text in the string with the
new character/text.
partition() Splits the string at the first occurrence of the argument string and returns a tuple
containing the part the before separator, argument string and the part after the
separator.
rpartition() Splits the string at the last occurrence of the argument string and returns a tuple
containing the part the before separator, argument string and the part after the
separator.
29. Python String Methods
29
Method Description
isalnum() Checks Alphanumeric Character.
isalpha() Checks if All Characters are Alphabets.
isdigit() Checks Digit Characters.
isspace() Checks Whitespace Characters.
isupper() Checks whether or not all characters in a string are uppercased or not.
islower() Checks if all alphabets in a string are lowercase alphabets.
istitle() Checks if the string is a title cased string.
30. capitalize()
• In Python, the capitalize() method converts first character of a string to
uppercase letter and lowercases all other characters, if any.
• The syntax of capitalize() is:
string.capitalize()
• function returns a string with the first letter capitalized and all other
characters lowercased. It doesn't modify the original string.
• Example:
string = "python is AWesome."
capitalized_string = string.capitalize()
print('Old String: ', string)
print('Capitalized String:', capitalized_string)
30
Old String: python is AWesome
Capitalized String: Python is awesome
31. center()
• The center() method returns a string which is padded with the specified
character.
• The syntax of center() method is:
string.center(width[, fillchar])
• It takes two arguments:
width - length of the string with padded characters
fillchar (optional) - padding character
• Example:
string = "Python is awesome"
new_string = string.center(24)
print("Centered String: ", new_string)
• Example:
string = "Python is awesome"
new_string = string.center(24, '*')
print("Centered String: ", new_string)
31
Centered String: ***Python is awesome****
Centered String: Python is awesome
32. count()
• The string count() method returns the number of occurrences of a substring
in the given string.
• It searches the substring in the given string and returns how many times the
substring is present in it.
• The syntax of center() method is:
string.count(substring, start=..., end=...)
• It takes 3 arguments:
substring - string whose count is to be found.
start (Optional) - starting index within the string where search starts.
end (Optional) - ending index within the string where search ends
• Example:
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
print("The count is:", count)
32
The count is: 2
33. count()
• Example 2:
string = "Python is awesome, isn't it?"
substring = "i"
count = string.count(substring, 8, 25)
print("The count is:", count)
33
The count is: 1
34. endswith()
• The string endswith() method check if the string ends with a specified
value.
• Example:
txt = "Hello, welcome to BVCOEL."
x = txt.endswith(".")
print(x)
34
True
35. casefold()
• The casefold() method is similar to the lower() method but it is more
aggressive.
• The casefold() method converts more characters into lower case compared
to lower() .
• Example:
text = 'groß'
# convert text to lowercase using casefold()
print('Using casefold():', text.casefold())
# convert text to lowercase using lower()
print('Using lower():', text.lower())
35
Using casefold(): gross
Using lower(): groß
36. find()
• Used for strings only.
• Syntax
– string.find(value, start, end)
• The find() method finds the first occurrence of the specified value.
• The find() method returns -1 if the value is not found.
• The find() method is almost the same as the index() method, the only
difference is that the index() method raises an exception if the value is not
found.
• Example:
txt = "Hello, welcome to BVCOEL."
x = txt.find("BVCOEL")
print(x)
36
18
37. rfind()
• Syntax
– string.rfind(value, start, end)
• The rfind() method finds the last occurrence of the specified value.
• The rfind() method returns -1 if the value is not found.
• The rfind() method is almost the same as the rindex() method..
• Example:
txt = "Hello, welcome to BVCOEL."
x = txt.find(“o")
print(x)
37
16
38. index()
• Can be used for strings, lists, tuples.
• Syntax
– string. index(value, start, end)
• The index() method finds the first occurrence of the specified value.
• The index() method raises an exception if the value is not found.
• The index() method is almost the same as the find() method, the only
difference is that the find() method returns -1 if the value is not found.
• Example:
txt = "Hello, welcome to BVCOEL."
x = txt. index("BVCOEL")
print(x)
38
18
39. rindex()
• Syntax
– string. rindex(value, start, end)
• The rindex() method finds the last occurrence of the specified value.
• The rindex() method raises an exception if the value is not found.
• The rindex() method is almost the same as the rfind()Example:
txt = "Hello, welcome to BVCOEL."
x = txt. rindex("BVCOEL")
print(x)
39
16