Python String
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.
s = "GfG"
print(s[1]) # access 2nd char
s1 = s + s[0] # update
print(s1) # print
Output
f GfGG
In this example, s holds the value “GfG” and is defined as a string.
Table of Content
Creating a String
Strings can be created using either single (‘) or double (“) quotes.
s1 = 'GfG'
s2 = "GfG"
print(s1)
print(s2)
Output
GfG GfG
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 on GeeksforGeeks"""
print(s)
s = '''I'm a
Geek'''
print(s)
Output
I am Learning Python String on GeeksforGeeks I'm a Geek
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 = "GeeksforGeeks"
# Accesses first character: 'G'
print(s[0])
# Accesses 5th character: 's'
print(s[4])
Output
G s
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.
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 = "GeeksforGeeks"
# Accesses 3rd character: 'k'
print(s[-10])
# Accesses 5th character from end: 'G'
print(s[-5])
Output
k G
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 = "GeeksforGeeks"
# Retrieves characters from index 1 to 3: 'eek'
print(s[1:4])
# Retrieves characters from beginning to index 2: 'Gee'
print(s[:3])
# Retrieves characters from index 3 to the end: 'ksforGeeks'
print(s[3:])
# Reverse a string
print(s[::-1])
Output
eek Gee ksforGeeks skeeGrofskeeG
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 = "geeksforGeeks"
# 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 = "G" + s[1:]
print(s)
Output
GeeksforGeeks
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 = "GfG"
# 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 geeks"
# Updating by creating a new string
s1 = "H" + s[1:]
# replacnig "geeks" with "GeeksforGeeks"
s2 = s.replace("geeks", "GeeksforGeeks")
print(s1)
print(s2)
Output
Hello geeks hello GeeksforGeeks
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 used replace() method to replace ‘geeks’ with ‘GeeksforGeeks’.
Common String Methods
Python provides a various built-in methods to manipulate strings. Below are some of the most useful methods.
len(): The len() function returns the total number of characters in a string.
s = "GeeksforGeeks"
print(len(s))
# output: 13
Output
13
upper() and lower(): upper() 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
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.
s = " Gfg "
# Removes spaces from both ends
print(s.strip())
s = "Python is fun"
# Replaces 'fun' with 'awesome'
print(s.replace("fun", "awesome"))
Output
Gfg 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)
Output
Hello World
We can repeat a string multiple times using * operator.
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.
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.
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.
s = "GeeksforGeeks"
print("Geeks" in s)
print("GfG" in s)
Output
True False
Quiz:
Related Articles:
- String Slicing
- f Strings in Python
- String Comparison in Python
- 7 Useful String Functions in Python
- Convert integer to String in Python
- Convert string to integer in Python
- String Concatenation
- Split String into list of Characters in Python
- Iterate over characters of strings in Python
- Python program to convert a string to list
- Python program to convert a list to string
- String Comparison in Python
- String Formatting in Python
- Python String Methods
- Python String Exercise
- Escape characters in Python
Recommended Problems:
- Welcome aboard – Python
- Repeat the Strings – Python
- String Functions I – Python
- Regex – Python
- Convert String to LowerCase
- String Duplicates Removal
- Reverse String
- Check Palindrome
- Closest Strings
- Divisible by 7
- Encrypt the String – II
- Equal point in a string of brackets
- Isomorphic Strings
- Check if two strings are k-anagrams or not
- Panagram Checking
- Minimum Deletions
- Number of Distinct Subsequences
- Check if string is rotated by two places
- Implement Atoi
- Validate an IP address
- License Key Formatting
- Find the largest word in dictionary
- Equal 0,1, and 2
- Add Binary Strings
- Sum of two large numbers
- Multiply two strings
- Look and say Pattern
- Longest Palindromic Subsequence
- Longest substring without repeating characters
- Substrings of length k with k-1 distinct elements
- Count number of substrings
- Interleaved Strings
- Print Anagrams together
- Rank the permutation
- A Special Keyboard
- Restrictive Candy Crush
- Edit Distance
- Search Pattern (KMP-Algorithm)
- Search Pattern (Rabin-Karp Algorithm)
- Search Pattern (Z-algorithm)
- Shortest Common Supersequence
- Number of words with K maximum distinct vowels
- Longest substring to form a Palindrome
- Longest Valid Parenthesis
- Distinct Palindromic Substrings