Strings
Membership Test
• We can test if a substring exists within a string
or not, using the keyword, ‘in’ and ‘not in’
• Example:
print('a' in 'program') True
print('at' not in 'battle‘ ) False
Traversing Python Strings
• Using for loop:
Example:
s='Hello' Output:
for i in s: Hello
print(i,end='
')
Traversing Python Strings
• Using for loop and range:
Example:
s='Hello' Output:
for i in H
range(len(s): e
print(s[i]) l
l
o
Traversing Python Strings
• Using while loop:
Example:
s='Hello' Output:
i=0 H
while i<len(s): e
print(s[i]) l
i+=1 l
o
ord() , chr()
• ord() function returns the Unicode code from a given
character.
Example: Output
print(ord("A“)) 65
print(ord(‘a')) 97
• chr() function is a built-in function that returns a string
representing a character whose Unicode code point is
the integer specified Output
Example: ASCII Value of 97
is:a
num = 97
print("ASCII Value of 97 is: ", chr(num))
Python String Methods
• upper() - converts the string to uppercase
• lower() - converts the string to lowercase
• replace() - replaces substring inside
• split() - splits the string as a list
• find() - returns the index of first occurrence of
substring
• index() - returns index of substring
• startswith()- checks if string starts with the
specified string
upper()
• The upper() method converts all lowercase
characters in a string into uppercase
characters and returns it. Syntax:
string.upper(
• Example
)
m = 'python is fun'
print(m.upper())
Output:
PYTHON IS FUN
lower()
• The lower() method converts all uppercase
characters in a string into lowercase
characters and returns it. Syntax:
string.lower()
• Example
message = 'PYTHON IS
FUN'
print(message.lower())
Output:
python is fun
replace()
The replace() method replaces each matching occurrence
of a substring with another string.
Syntax: str.replace(old, new [, count])
old - the old substring we want to replace
new - new substring which will replace the old substring
count (optional) - the number of times you want to replace the old substring with
the new string
If count is not specified, the replace() method replaces all occurrences of
the old substring with the new string.
Example
text = 'bat ball‘
Output:
new= text.replace('ba', 'ro') rot roll
print(new)
replace()
If count is specified, the replace() method replaces all
occurrences of the old substring with the new string.
Example 2:
s = 'PythonPython'
print(s.replace('yth', "ige",1))
Output:
PigeonPython
split()
• The split() method splits a string at the
specified separator and returns a list of
substrings.
Syntax: str.split(separator,
maxsplit)
separator (optional)- Delimiter at which splits occur. If not provided, the
string is splitted at whitespaces.
Example
cars = 'BMW-Tesla-Range Rover'
print(cars.split('-'))
Output:
['BMW', 'Tesla', 'Range Rover']
find()
• The find() method returns the index of first
occurrence of the substring (if found). If not
found, it returns -1.
Syntax: str.find(sub [, start[, end]] )
sub - It is the substring to be searched in the str string.
start and end (optional) - The range str[start:end] within
which substring is searched.
Example:
m = 'Python is a programming language'
Output: 12
print(m.find(‘program'))
m = ‘program programming program'
Output: 8
print(m.find(‘program‘,6,15))
index()
• The index() method returns the index of a substring
inside the string (if found). If the substring is not
found, it raises an exception(ValueError exception)
• Syntax: str.index(sub[, start[,
end]] )
sub - substring to be searched in the string str.
start and end(optional) - substring is searched within str[start:end]
text = 'Python is fun'
result = Output:
text.index('is‘,1,10) 7
print(result)
rfind() Finds the last occurrence of the Example:
specified value. Returns -1 if the txt = ’hi hello hi"
value is not found. print(txt.rfind(‘hi’))
Output:
string.rfind(value, start, end) 9
rindex() Searches the string for a specified Example:
value and returns the last txt = ’hi hello hi"
position of where it was found print(txt.rindex(‘hi’))
Output:
string.rfind(value, start, end) 9
If the substring is not found, it Example:
raises a ValueError exception txt = ’hi hello hi"
print(txt.rindex(‘gi’))
Output:
ValueError Exception
startswith() , endswith()
The startswith() method returns True if the string starts with the
specified value, otherwise False.
Syntax: string.startswith(value, start, end)
The endswith() method returns True if the string ends with the
specified value, otherwise False.
Syntax: string.endswith(value, start, end)
Example
txt ="Hello, Good Morning“ Output:
print(txt.startswith("Hel")) True
print(txt.endswith("ing")) True
join()
• The join() method takes all items in an iterable
and joins them into one string.
• A separator string must be specified to join the
strings.
Syntax: seperator.join(iterable) list
tuple
Example: Example:
s = (“Hi", “Hello", “Hey") m = [‘I’,’am’,’a’,’student’]
print(‘@’.join(s)) print(‘ ’.join(m))
Output: Output:
Hi@Hello@Hey I am a student
enumerate()
• The enumerate() function adds a counter to an iterable
and returns it (the enumerate object).
Syntax: enumerate(iterable, start=0)
start (optional) - enumerate() starts counting from this number
iterable - a sequence, an iterator, or objects that support iteration
You can convert enumerate objects to list and tuple using
list() and tuple() functions
Example:
grocery = ['bread', 'milk', 'butter']
e = enumerate(grocery)
print(type(e))
Output:
print(list(e))
<class 'enumerate'>
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
Method Description Example Output
Returns True if all characters in t = “ABC1234"
isalnum() the string are alphanumeric print( t.isalnum()) True
Returns True if all characters in t = “ABC"
isalpha() the string are in the alphabet print( t.isalpha()) True
Returns True if all characters in t = “1234"
isdigit() the string are digits print( t.isdigit()) True
t = “ABC“
islower() Returns True if all characters in m=“hello” False
the string are lower case print( t.islower()) True
print(m.islower())
isnumeric() Returns True if all characters in t = “67685"
the string are numeric print( t.isnumeric()) True
Returns True if all characters in t = ‘ ‘
isspace() the string are whitespaces print( t.isspace()) True
Returns True if all characters t = “ABC"
isupper() in the string are upper case print( t.isupper()) True
isidentifier() Returns True if the string is a
valid identifier
s=‘hello’
print(s.isidentifier()) True
Method Description Example Output
Converts the first character to
t = “hello Gi"
capitalize() upper case, and remaining
print( t.capitalize()) Hello gi
characters to lowercase
s = “hello good
Converts the first character of Hello Good
title() each word to upper case morning" Morning
print( s.title())
Returns the number of times a
specified value appears in the c = “Banana"
count() string print(c.count(‘a’)) 3
string.count(value, start, end)
Removes all leading and t = “ Apple "
strip() trailing whitespaces in string print( t.strip()) Apple
Removes all leading t = “ Apple "
lstrip() whitespaces in string print( t.lstrip()) Apple
Removes all trailing t = “ Apple "
rstrip() whitespaces in string print( t.rstrip()) Apple
Swaps cases, lower case becomes t = "Hello I am ALEX"
swapcase() upper case and vice versa print(t.swapcase()) hELLO i AM alex
Method Description Example Output
Returns left aligned string, using a
specified character (space is t = “hi"
ljust() default) as the fill character. print( t.ljust(8,’*’)) hi******
string.ljust(width, fillcharacter)
Returns right aligned string, using
a specified character (space is s = “hi"
rjust() default) as the fill character. print( s.rjust(8,’*’)) ******hi
string.rjust(width, fillcharacter)
Center aligns the string, using a
specified character (space is s = "banana"
center() default) as the fill character print(s.center(12,’*’)) ***banana***
string.center(width, fillcharacter)
Fills the string with a specified
number of 0 values at the c = “5678"
zfill() beginning print(c.zfill(8)) 00005678
string.zfill(width)
Function Description Example Output
Returns the length of the t = ‘Apple’
len() string print( len(t)) 5
Returns the character having m=‘hello’
max() the highest ASCII value print( max(m)) o
Returns the character having t = “Apple"
min() the lowest ASCII value print( min(t)) A
Example – String constants