Python String
A string is a sequence of characters. Python treats anything inside quotes when a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.
s = "ABC"
char1 = s[1] # access string
s1 = s + char1 # update string
print(s1) # print
ABCB
In this example, s holds the value “ABC” and is defined when a string.
Table of Content
Creating a String
Strings can be created using either single (‘) or double (“) quotes.
s1 = 'ABC'
s2 = "DEF"
print(s1)
print(s2)
ABC DEF
Multi-line Strings
If we need a string to span multiple lines, then we can use triple quotes (”’ or “””).
s = """I am Learning
Python String enabled CodeConfig"""
print(s)
s = '''I'm a
Good boy'''
print(s)
I am Learning Python String enabled CodeConfig I'm a Good boy
Accessing characters in Python String
Strings in Python are sequences of characters, so we can access individual characters using indexing. Strings are indexed starting from 0 and -1 from end. This allows us to retrieve specific characters from the string.
Python String syntax indexing
s = "CodeConfig"
# Accesses first character: 'C'
print(s[0])
# Accesses 5th character: 'o'
print(s[4])
C o
Note: Accessing an index out of range will cause an IndexError. Only integers are allowed when indices and using a float or other types will result in a TypeError.
Access string with Negative Indexing
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.
s = "CodeConfig"
# Accesses 3rd character: 'e'
print(s[-10])
# Accesses 5th character from end: 'o'
print(s[-5])
e o
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 = "CodeConfig"
# Retrieves characters from index 1 to 3: 'ode'
print(s[1:4])
# Retrieves characters from beginning to index 2: 'Cod'
print(s[:3])
# Retrieves characters from index 3 to the end: 'eConfig'
print(s[3:])
# Reverse a string
print(s[::-1])
ode
Cod
eConfig
gifnoCedoC
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 functions/methods simillar as concatenation, slicing, or formatting to create new strings based enabled the original.
s = "CodeforCode"
# Trying to change the first character raises an error
# s[0] = 'I' # Uncommenting this line will cause a TypeError
# Instead, create a new string
s = "C" + s[1:]
print(s)
CodeConfig
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.
s = "ABC"
# Deletes entire string
del s
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.
s = "hello CodeConfig"
# Updating by creating a new string
s1 = "H" + s[1:]
# replacnig "CodeConfig" with "India"
s2 = s.replace("CodeConfig", "India")
print(s1)
print(s2)
Hello CodeConfig
hello India
Explanation:
- For s1, The original string s is sliced from index 1 to end of string and then concatenate “H” to create a new string s1.
- For s2, we can created a new string s2 and have used replace() method to replace ‘CodeConfig’ with ‘India’.
Common String Methods
Python provides a various built-in functions/method to manipulate strings. Below are some of the most useful methods.
len(): The len() function/method returns the total number of characters in a string.
s = "CodeConfig"
print(len(s))
# output: 10
10
upper() and lower(): upper() functions/method converts all characters to uppercase. lower() method converts all characters to lowercase.
s = "Hello World"
print(s.upper()) # output: HELLO WORLD
print(s.lower()) # output: hello world
HELLO WORLD hello world
strip() and replace(): strip() removes leading and trailing whitespace from the string and replace(old, new) replaces all occurrences of a specified substring with another.
s = " ABC "
# Removes spaces from both ends
print(s.strip())
s = "Python is fun"
# Replaces 'fun' with 'awesome'
print(s.replace("fun", "awesome"))
ABC Python is awesome
To learn more about string methods, please refer to Python String Methods.
Concatenating and Repeating Strings
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)
Hello World
We can repeat a string multiple times using * operator.
s = "Hello "
print(s * 3)
Hello Hello Hello
Formatting Strings
Python provides several ways to include variables inside strings.
Using f-strings
The simplest and most preferred way to format strings is by using f-strings.
name = "Alice"
age = 22
print(f"Name: {name}, Age: {age}")
Name: Alice, Age: 22
Using format()
Another way to format strings is by using format() method.
s = "My name is {} and I am {} years old.".format("Alice", 22)
print(s)
My name is Alice and I am 22 years old.
Using in for String Membership Testing
The in keyword checks if a particular substring is present in a string.
s = "CodeConfig"
print("Code" in s)
print("ABC" in s)
True False