Strings in Python
Strings in Python
A string is a sequence of characters. Python treats anything inside quotes as a string. This
includes letters, numbers, and symbols. Python has no character data type so single
character is a string of length 1.
Creating a String-
Strings can be created using either single (‘) or double (“) quotes.
s1 = ‘ABC'
s2 = “XYZ"
print(s1)
print(s2)
Multi-line Strings-
If we need a string to span multiple lines then we can use triple quotes (”’ or “””).
at Hindustan"""
print(s)
# output
# I am in second
# year at Hindustan
s = “LITERATURE"
print(s[0]) #ouput=L
print(s[4]) #output=R
Note: Accessing an index out of range will cause an IndexError. Only integers are allowed as
indices and using a float or other types will result in a TypeError.
Python allows negative address references to access characters from back of the String,
e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
# sample program
s = “LITERATURE"
print(s[-10])
print(s[-5])
String Slicing
Slicing is a way to extract portion of a string by specifying the start and end indexes.
The syntax for slicing is string[start:end], where start starting index and end is stopping
index (excluded).
s = “ALLTHEBEST"
print(s[1:4])
print(s[:3])
print(s[3:])
# Reverse a string
print(s[::-1])
#output is ‘TSEBEHTLLA’
String Immutability
Strings in Python are immutable. This means that they cannot be changed after they are
created. If we need to manipulate strings then we can use methods like concatenation,
slicing, or formatting to create new strings based on the original.
s = “LOVEINDIA"
s = “I" + s[0:]
print(s)
#output is ‘ILOVEINDIA’
Deleting a String
In Python, it is not possible to delete individual characters from a string since strings are
immutable. However, we can delete an entire string variable using the del keyword.
# example
s = "GfG"
Note: After deleting the string using del and if we try to access s then it will result in
a NameError because the variable no longer exists.
Updating a String
To update a part of a string we need to create a new string since strings are immutable.
# example
s = "hello Alice“
S1 = "H" + s[1:]
print(s1)
# replace “Alice" with “Varun"
print(s2)
Common String Methods- Python provides a various built-in methods to manipulate strings.
len(): The len() function returns the total number of characters in a string.
s = “Computer"
print(len(s))
# output: 8
s = "Hello World"
print(s.strip())
s = "Python is fun"
print(s.replace("fun", "awesome"))
We can concatenate strings using + operator and repeat them using * operator.
Strings can be combined by using + operator.
s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3)
s = "Hello "
print(s * 3)
Formatting Strings
Using f-strings
The simplest and most preferred way to format strings is by using f-strings.
name = "Alice"
age = 22
Using format()
# example program
print(s1)
Using in for String Membership Testing
s = “ANECDOTE"