Strings in Python
CSE304 – Python Programming with Web Frameworks
What are Strings?
Python string is a collection of Unicode characters.
Python strings can be enclosed in single, double or triple quotes.
'BlindSpot’
"BlindSpot"
' ' 'BlindSpot' ' ‘
"""Blindspot"""
if there are characters like ' " or \ within a string, they can be
retained in two ways:
(a) Escape them by preceding them with a \
(b) Prepend the string with a 'r' indicating that it is a raw string
CSE304 - Python Programming with Web Frameworks 2
Strings
Multiline strings can be created in 3 ways:
All but the last line ends with \
Enclosed within """some msg """ or ' ' 'some msg' ' '- (‘one
msg’ 'another msg')
CSE304 - Python Programming with Web Frameworks 3
Accessing String Elements
String elements can be accessed using an index value , starting with
0 . Negative index value is allowed.
The last character is considered to be at index -1
CSE304 - Python Programming with Web Frameworks 4
positive and negative indexing
CSE304 - Python Programming with Web Frameworks 5
String slicing
s[start : end] - extract from start to end - 1.
s[start :] - extract from start to end.
s[: end] - extract from start to end - 1.
s[-start :] - extract from -start (included) to end.
s[: -end] - extract from beginning to -end - 1.
Using too large an index reports an error, but using too large
index while slicing is handled elegantly.
msg = 'Rafting’
print(msg[3:100]) # prints elements from 't' up to end of string
print(msg[100]) # error since 100 th element doesn't exist
CSE304 - Python Programming with Web Frameworks 6
String striding
s[start : end: step]
extract from start to end – 1 with step value
If step value is negative, then striding (stepping) the string
from backward direction.
If step value is positive, then striding the string from
forward direction.
CSE304 - Python Programming with Web Frameworks 7
String Properties
Python strings are immutable—they cannot be changed.
s = 'Hello’
s[0] = 'M’ # rejected, attempt to mutate string
s = 'Bye’ # s is a variable, it can change
Strings can be concatenated using +.
msg3 = ms1 + msg2
Strings can be replicated during printing. ( str * i)
print('-‘*50) # prints 50 dashes
Whether one string is part of another can be found out using
in.
print('e' in 'Hello’) # prints True
print('z' in 'Hello’) # print False
CSE304 - Python Programming with Web Frameworks 8
Built-in Functions
msg = 'Surreal’
print(len(msg)) # prints 7 - length of string
print(min(msg)) # prints S - character with min value
print(max(msg)) # prints u - character with max
value
print(sorted(msg)) # prints sorted order of individual
characters in given string
Rev=list(reversed(msg)) # returns a list of reverse order given
string
CSE304 - Python Programming with Web Frameworks 9
String Methods
When we create a string a nameless object of type str is
created.
msg = 'Surreal’
print(type(msg)) # prints <class 'str’>
print(id(msg)) # prints 33720000
Address of the nameless str object is stored in msg
which is returned by the built-in id( ) function.
CSE304 - Python Programming with Web Frameworks 10
Strings methods
isalpha( ) - checks if all characters in string are alphabets.
isdigit( ) - checks if all characters in string are digits.
isalnum( ) - checks if all characters in string are alphabets or
digits.
islower( ) - checks if all characters in string are lowercase
alphabets.
isupper( ) - checks if all characters in string are uppercase
alphabets.
startswith( ) - checks if string starts with a value.
endswith( ) - checks if string ends with a value.
CSE304 - Python Programming with Web Frameworks 11
String Methods
lstrip( ) - removes whitespace from the left of string including \t.
rstrip( ) - removes whitespace from the right of string including
\t.
strip( ) - removes whitespace from left and right
# split and partition
split( ) - split the string at a specified separator string.
partition( ) - partitions string into 3 parts at first
occurrence of specified string. (before match, match, after
match()
count(str) returns the number of occurrences of characters in
the string.
CSE304 - Python Programming with Web Frameworks 12
String join
join - different than concatenation. It joins string to each
element of string1 except last.
join(string1)
msg = 'Hello’
print([Link]('l', 'L')) # replaces l with L in Hello
print("-".join("Hello")) # prints H-e-l-l-o
CSE304 - Python Programming with Web Frameworks 13
String Conversions
Two types of string conversions are required frequently:
- Converting the case of characters in string
- Converting numbers to string and vice versa
Case conversions can be done using str methods:
upper( ) - converts string to uppercase.
lower( ) - converts string to uppercase.
capitalize( ) - converts first character of string to
uppercase
title( ) - converts first character of each word to
uppercase.
swapcase( ) - swap cases in the string.
CSE304 - Python Programming with Web Frameworks 14
Built-in functions
Built-in functions are used for string to number conversions
str( ) - converts an int, float or complex to string
int( ) - converts a numeric string to int
float( ) - converts a numeric string to float
complex( ) - converts a numeric string to complex
CSE304 - Python Programming with Web Frameworks 15
Built-in functions
chr( ) returns a string representing its Unicode value and ord( ) does
the reverse.
CSE304 - Python Programming with Web Frameworks 16
String Comparison
s1 = "Bombay"
s2 = "bombay"
s3 = "Nagpur"
s4 = "Bombaywala"
s5 = "Bombay"
print(s1 == s2) # displays False
print(s1 == s5) # displays True
print(s1 != s3) # displays True
print(s1 > s5) # displays False
print(s1 < s2) # displays True
print(s1 <= s4) # displays True
CSE304 - Python Programming with Web Frameworks 17
find() and replace()
find(str) returns the position where first search character is
found.
To search subsequent character is started from pos + 1.
When search character is not found search( ) returns -1.
index(str) – similar to find(), returns position of search string, if
not found raise an error.
replace(old, new, i)- replaces the old string with new string
third parameter indicate number of replacement to be
done, it is optional.
CSE304 - Python Programming with Web Frameworks 18