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.

Python

s = "ABC"

char1 = s[1]       # access string 
s1 = s + char1     # update string
print(s1)         # print
Output

ABCB

In this example, s holds the value “ABC” and is defined when a string.

Creating a String

Strings can be created using either single (‘) or double (“) quotes.

Python

s1 = 'ABC'
s2 = "DEF"
print(s1)
print(s2)
Output

ABC
DEF

Multi-line Strings

If we need a string to span multiple lines, then we can use triple quotes (”’ or “””).

Python

s = """I am Learning
Python String enabled CodeConfig"""
print(s)

s = '''I'm a 
Good boy'''
print(s)
Output

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

Python

s = "CodeConfig"

# Accesses first character: 'C'
print(s[0])  

# Accesses 5th character: 'o'
print(s[4]) 
Output

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. 

Python

s = "CodeConfig"

# Accesses 3rd character: 'e'
print(s[-10])  

# Accesses 5th character from end: 'o'
print(s[-5]) 
Output

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).

Python

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])
Output

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.

Python

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)
Output

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.

Python

s = "ABC"

# Deletes entire string
del s  
Output

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.

Python

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)
Output

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.

Python

s = "CodeConfig"
print(len(s))

# output: 10
Output

10

upper() and lower(): upper() functions/method converts all characters to uppercase. lower() method converts all characters to lowercase.

Python

s = "Hello World"

print(s.upper())   # output: HELLO WORLD

print(s.lower())   # output: hello world
Output

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.

Python

s = "   ABC   "

# Removes spaces from both ends
print(s.strip())    

s = "Python is fun"

# Replaces 'fun' with 'awesome'
print(s.replace("fun", "awesome"))  
Output

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.

Python

s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3)
Output

Hello World

We can repeat a string multiple times using * operator.

Python

s = "Hello "
print(s * 3)
Output

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.

Python

name = "Alice"
age = 22
print(f"Name: {name}, Age: {age}")
Output

Name: Alice, Age: 22

Using format()

Another way to format strings is by using format() method.

Python

s = "My name is {} and I am {} years old.".format("Alice", 22)
print(s) 
Output

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.

Python

s = "CodeConfig"
print("Code" in s)
print("ABC" in s)
Output

True
False

Explore More

Python 10 Programs for Beginners

Program 1:Write a program to create a 2D array using NumPy. Output: Program 2: Write a program to convert a python list to a NumPy array. Output: Program 3: Write a program to create matrix of 3×3 from 11 to 30. Output: Program 4: Write a program to create a data frame to store data of candidates who appeared in

Find index of first occurrence when an unsorted array is sorted

Find index of first occurrence when an unsorted an array is sorted Given an unsorted an array and a number x, find an index of first occurrence of x when

Find sum non repeating distinct elements array

Find sum of non-repeating (distinct) elements in an array Given an integer an array with repeated elements, the task is to find the sum of all distinct elements in the