Strings in Python
Learning objective
• What is a String?
• Accessing values in Strings
• Updating Strings
• String Special Operators
• Built-in String Methods
Strings
• Strings are amongst the most popular types in Python.
• We can create them simply by enclosing characters in quotes.
• Python treats single quotes the same as double quotes.
• Creating strings is as simple as assigning a value to a variable.
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing values in Strings
• Python does not support a character type; these are treated as
strings of length one, thus also considered a substring.
• To access substrings, use the square brackets for slicing along
with the index or indices to obtain your substring.
s = "Python Programming"
print(s[0])
print(s[1])
print(s[1:5])
Updating/Deleting Strings
• Updating or deleting of characters from a String is not allowed.
• This will cause an error because item assignment or item deletion
from a String is not supported.
• Although deletion of entire String is possible with the use of a
built-in del keyword.
• This is because Strings are immutable, hence elements of a String
cannot be changed once it has been assigned.
• Only new strings can be reassigned to the same name.
Deleting entire String
emp_name="salim"
del emp_name #Deleting entire String
# Try to access the string after deletion, it will raise an error
try:
print(emp_name)
except NameError as e:
print("Error: ", e)
String indexing
• Indexing is the process of finding a specific element within a
sequence of elements through the element’s position.
M O N T Y P Y T H O N
Left to Right: 0 1 2 3 4 5 6 7 8 9 10 11
Right to Left: -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Updating/Deleting String elements
name="salim"
name[0] = ‘A'
print(name)
# TypeError: 'str' object does not support item assignment
name="salim"
del name[0]
print(name)
# TypeError: 'str' object doesn't support item deletion
name="salim“ # Attempt to change the first character to 'S'
try:
name[0] = ‘A’ # This will raise a TypeError
except TypeError as e:
print("Error: ", e)
name = "salim“ # Attempt to delete the first character
try:
del name[0]
except TypeError as e: # This will raise a TypeError
print("Error", e)
String Special Operators
+ Concatenation - Adds values on either side of the operator
* Repetition - Creates new strings, concatenating multiple copies of
the same string
[] Slice - Gives the character from string index
[ : ] Range Slice - Gives the characters from the given range
in Membership - Returns true if a character exists in the given string
not in Membership - Returns true if a character does not exist in the
given string
r/R Raw String
Concatenation
• Concatenation is a word for stringing strings together. In Python,
concatenation is done with the + operator.
• It is often used to combine variables with literals.
user_name = input("What is your name? ")
greeting = "Hello, " + user_name + "!"
print(greeting)
For update, slice the original string and
concatenate parts to form a new one
name1 = "salim"
# Attempt to update the first character
name2 = "A" + name1 [1:]
print (name2)
name1="salim"
# Attempt to delete the first character
name2 = name1 [:0] + name1[1:]
print(name2)
String Special Operators
a="""Hello"""
b='World'
print(a+b)
print(a*2)
print(b[2])
c='W'
print(c in b)
print(c not in b)
print(r"Your father's name is \n")
Built-in String Methods
• Python includes built-in methods to manipulate strings :
• capitalize() :Capitalizes first letter of string.
• center(width, fillchar) :Returns a space-padded string with the
original string centered to a total of width columns.
• count() : The method count() returns the number of occurrences
of substring sub in the range [start, end].
• find():It determines if string str occurs in string, or in a substring of
string if starting index beg and ending index end are given.
string1 = "learning python is interesting!"
string2 = string1.capitalize()
print(string2)
string1 = "Learning is Fun!"
string2 = string1.center(30,'*')
print(string2)
string1 = "Python. I like Python Programming!"
string2 = string1.count("Python")
print(string2)
string1 = "I like Python Programming!"
string2 = string1.find("Python")
print("Index of 'Python': ",string2)
Built-in String Methods
• index(): It determines if string str occurs in string or in a substring of
string if starting index beg and ending index end are given. This
method is same as find(), but raises an exception if sub is not found.
• isalnum(): It checks whether the string consists of alphanumeric
characters.
• isalpha() : The method isalpha() checks whether the string consists
of alphabetic characters only.
• isdigit() : The method isdigit() checks whether the string consists of
digits only.
string1 = "I like Python Programming!"
string2 = string1.index("Python")
print("Index of 'Python': ",string2)
string1 = "Python312"
string2 = "Python Programming"
print(string1.isalnum())
print(string2.isalnum())
string1 = "Python"
string2 = "Python312"
print(string1.isalpha())
print(string2.isalpha())
string1 = "312"
string2 = "Python312"
print(string1.isdigit())
print(string2.isdigit())
Built-in String Methods
• islower(): The method islower() checks whether all the case-based
characters (letters) of the string are lowercase.
• isnumeric() :The method isnumeric() checks whether the string consists
of only numeric characters. This method is present only on Unicode
objects.
• isspace() :The method isspace() checks whether the string consists of
whitespace.
• isupper() : The method isupper() checks whether all the case-based
characters (letters) of the string are uppercase.
string1 = "python"
print(string1.islower())
string2 = "123"
print(string2.isnumeric())
string3 = "十一" #11 in chinese language
print(string3.isnumeric())
string4 = " "
print(string4.isspace())
string5 = "python"
print(string5.isupper())
Built-in String Methods
• len() : It returns the length of the string.
• lower() :The method lower() returns a copy of the string in which all
case-based characters have been lowercased.
• max() :The method max() returns the max alphabetical character
from the string str.
• min() : The method min() returns the min alphabetical character from
the string str.
• replace() :The method replace() returns a copy of the string in which
the occurrences of old have been replaced with new, optionally
restricting the number of replacements to max.
string1 = "PYTHON"
print(len(string1))
print(string1.lower())
print(string1.upper())
print(string1.capitalize())
print(string1.title())
print(string1.swapcase())
print(max(string1))
print(min(string1))
string2 = "Hi Everyone"
print(string2.replace("Hi","Hello"))
You have learnt:
• What is a String?
• Accessing values in Strings
• Updating Strings
• String Special Operators
• Built-in String Methods