EURO INTERNATIONAL SCHOOL,
SEC-10, GURUGRAM
SESSION- 2020-21 CLASS- XII
CH-2 PYTHON REVISION TOUR- II SUBJECT- COMPUTER
TOPIC- STRINGS IN PYTHON SCIENCE
NAME: ROLL NO:
Topics to be Covered:-
Strings
Lists
Tuples
Dictionaries
String:-
String literals in python are surrounded by either single quotation marks, or double quotation marks.
In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a
character data type, a single character is simply a string with a length of 1. Square brackets can be used to
access elements of the string.
Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters
on your screen, internally it is stored and manipulated as a combination of 0's and 1's.
This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and
Unicode are some of the popular encoding used.
In Python, a string is a sequence of Unicode characters. Unicode is an information technology standard for the
consistent encoding, representation, and handling of text expressed in most of the world's writing systems.
The Unicode Standard provides a unique number for every character, no matter what platform, device,
application or language.
Char Unicode HTML named code
& U+0026 &
• U+2022 •
Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can
be used in Python but generally used to represent multiline strings and docstrings.
Example
# all of the following are equivalent
my_string = 'Hello'
print(my_string)
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)
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
a = "Hello"
print(a)
How to access characters in a string?
We can access individual characters using indexing and a range of characters using slicing. Index starts from
0. Trying to access a character out of index range will raise an IndexError. The index must be an integer. We
can't use float or other types, this will result into TypeError.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a
string by using the slicing operator (colon).
str = 'programiz'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
If we want to access a range, we need the index that will slice the portion from the string.
How to change or delete a string?
Strings are immutable. This means that elements of a string cannot be changed once it has been assigned. We
can simply reassign different strings to the same name.
>>> my_string = 'programiz'
>>> my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
>>> my_string = 'Python'
>>> my_string
'Python'
We cannot delete or remove characters from a string. But deleting the string entirely is possible using the
keyword del.
>>> del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
...
NameError: name 'my_string' is not defined
Traversing/ Accessing of String:-
Traversing means access or iterate through the elements of string, one character at a time.
A = “hello”
for ch in A:
print (ch, end = ‘ ‘)
String Operations
There are many operations that can be performed with string which makes it one of the most used datatypes in
Python.
Concatenation of Two or More Strings
Joining of two or more strings into a single one is called concatenation.
The + operator does this in Python. Simply writing two string literals together also concatenates them.
The * operator can be used to repeat the string for a given number of times.
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
Writing two string literals together also concatenates them like + operator.
If we want to concatenate strings in different lines, we can use parentheses.
>>> # two string literals together
>>> 'Hello ''World!'
'Hello World!'
>>> # using parentheses
>>> s = ('Hello '
... 'World')
>>> s
'Hello World'
String Slicing
To access a range of characters in the String, method of slicing is used. Slicing in a String is done by using a
Slicing operator (colon).
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
String Membership Test (Membership )
2 membership operator we have- in and not in
We can test if a sub string exists within a string or not, using the keyword in.
>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False
>>> 'a' not in 'program'
False
>>> 'at' in 'battle'
True
String Methods
Python has a set of built-in methods that you can use on strings.
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Try it Yourself »
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in the string where the
placeholders {} are:
Example
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
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
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
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
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning