Python strings are a key data type for handling text. This article explains how they work, ways to manipulate them, and useful built-in methods. It also covers formatting, slicing, and real-world examples to help you use strings effectively.
Contents:
- Introduction to Python Strings
- Creating Strings in Python
- Accessing Characters in a String in Python
- Modifying Strings in Python
- String Immutability in Python
- String Formatting in Python
- Updating a String in Python
- Deleting a String in Python
- Escape Characters in Python
- String Methods in Python
- Raw Strings in Python
- FAQs on Strings in Python
Introduction to Python Strings
Python strings store and handle text as sequences of characters. They are a widely used data type with many built-in methods for formatting, slicing, and modifying text. You can create strings using single (‘ ‘), double (” “), or triple (”’ ”’ or “”” “””) quotes, making text handling flexible and convenient.
Creating Strings in Python
Strings in Python are sequences of characters enclosed within quotes. They can be created using single, double, or triple quotes.
1. Using Single Quotes
subject = 'Python' print(subject)
Output:
Python
2. Using Double Quotes
# Sanfoundry Topic Name topic = "Data Structures" print(topic)
Output:
Data Structures
3. Using Triple Quotes for Multi-line Strings
# Sanfoundry Quiz Instructions instructions = '''1. Attempt all questions. 2. No negative marking.''' print(instructions)
Output:
1. Attempt all questions. 2. No negative marking.
4. Creating an Empty String
# Empty String Declaration empty_string = "" print("Length:", len(empty_string))
Output:
Length: 05. Creating a String with Escape Characters
course = "Sanfoundry's \"Python\" Course" print(course)
Output:
Sanfoundry's "Python" CourseAccessing Characters in a String in Python
Strings in Python are sequences of characters that you can access using indexing and slicing techniques.
1. Accessing Characters Using Indexing
Indexing lets you access individual characters based on their position. The first character has an index of 0, while the last character has an index of -1.
text = "Python" print(text[0]) # First character print(text[3]) # Fourth character print(text[-1]) # Last character
Output:
P h n
2. Accessing a Range of Characters Using Slicing
Slicing extracts a part of the string using the syntax: string[start:end]. It includes characters from the start index up to end – 1.
topic = "Data Structures" # Accessing substring using slicing print(topic[0:4]) # First four characters print(topic[5:]) # Characters from index 5 to the end print(topic[:4]) # First four characters (same as [0:4]) print(topic[-4:]) # Last four characters
Output:
Data Structures Data ures
3. Using a Loop to Access Each Character
subject = "DBMS" for char in subject: print(char, end=" ")
Output:
D B M S
Modifying Strings in Python
Strings in Python are immutable, meaning their content cannot be modified directly. However, you can create modified versions of strings using various techniques.
1. Changing Case Using upper() and lower()
upper() – Converts all characters to uppercase. lower() – Converts all characters to lowercase.
subject = "Python Course" print(subject.upper()) # Convert to uppercase print(subject.lower()) # Convert to lowercase
Output:
PYTHON COURSE python course
2. Replacing Substrings Using replace()
The replace() method in Python is used to replace a specific substring within a string with another substring. It does not modify the original string but returns a new modified version.
Syntax:
string.replace(old, new, count)
Example:
course = "Data Structures" # Replace 'Data' with 'Algo' modified_course = course.replace("Data", "Algo") print(modified_course)
Output:
Algo Structures
3. Changing a String Using Concatenation
Since strings in Python are immutable, you cannot modify them directly. However, you can create a new string by concatenating existing strings using the + operator.
module1 = "DBMS" module2 = "OS" combined = module1 + " and " + module2 print(combined)
Output:
DBMS and OS4. Removing Whitespace Using strip()
strip() – Removes leading and trailing whitespaces. lstrip() – Removes leading whitespaces. rstrip() – Removes trailing whitespaces.
Example:
topic = " Python Programming " print(topic.strip()) print(topic.lstrip()) print(topic.rstrip())
Output:
Python Programming Python Programming Python Programming
5. Splitting and Joining Strings
split() – Splits a string into a list of substrings. join() – Joins a list of strings into a single string.
# Sanfoundry Quiz Topics quiz = "Python, Java, DBMS" quiz_list = quiz.split(", ") print(quiz_list) # Output: ['Python', 'Java', 'DBMS'] # Join back to a string new_quiz = " and ".join(quiz_list) print(new_quiz)
Output:
['Python', 'Java', 'DBMS'] Python and Java and DBMS
6. Reversing a String
Strings can be reversed using slicing.
module = "AI" reversed_module = module[::-1] print(reversed_module)
Output:
IA
String Immutability in Python
In Python, strings are immutable, meaning you cannot modify their content after creation. Any operation that appears to modify a string actually creates a new string instead of changing the original one.
Example: Strings Cannot Be Modified Directly
text = "Sanfoundry" text[0] = "H" # This will cause an error
Error:
TypeError: 'str' object does not support item assignment
Modifying a String Indirectly
To modify a string, you must create a new one using concatenation, replacement, or slicing:
text = "Sanfoundry" new_text = "H" + text[1:] # Replacing 'S' with 'H' print(new_text) # Output: Hanfoundry
String Formatting in Python
String formatting in Python allows you to insert variables into a string in a flexible and readable way. There are three main methods for string formatting in Python.
1. Using format() Method
The format() method inserts values into placeholders defined by {}.
# Sanfoundry Quiz Details subject = "Python" score = 95 result = "You scored {} in {} quiz.".format(score, subject) print(result)
Output:
You scored 95 in Python quiz.
2. Using f-Strings
f-Strings are prefixed with f and allow embedding expressions inside curly braces {}.
# Sanfoundry Course Info course = "DBMS" duration = 30 info = f"{course} course is for {duration} hours." print(info)
Output:
You scored 95 in Python quiz. DBMS course is for 30 hours.
3. Using % Operator (Old Method)
% is used as a placeholder for string, integer, and other data types.
# Sanfoundry Certification Info cert = "Java" hours = 40 details = "The %s certification requires %d hours." % (cert, hours) print(details)
Output:
The Java certification requires 40 hours.4. Aligning Text Using format()
format() can align text using < (left), > (right), and ^ (center).
# Sanfoundry Result Summary print("{:<10} {:^10} {:>10}".format("Name", "Score", "Grade")) print("{:<10} {:^10} {:>10}".format("Raj", 90, "A")) print("{:<10} {:^10} {:>10}".format("Neha", 85, "B"))
Output:
Name Score Grade Raj 90 A Neha 85 B
5. Formatting Numbers with format()
You can format floating-point numbers with precision.
# Sanfoundry Quiz Time time_taken = 45.6789 formatted_time = "Quiz completed in {:.2f} minutes.".format(time_taken) print(formatted_time)
Output:
Quiz completed in 45.68 minutes.
Updating a String in Python
Since strings are immutable, you cannot modify a part of a string directly. However, you can assign a new value to the variable instead.
# Original Sanfoundry Subject subject = "Python" # Updating by creating a new string subject = "Java" print("Updated Subject:", subject)
Output:
Updated Subject: Java
Deleting a String in Python
Python allows you to delete a string completely using the del keyword. However, since strings are immutable, you cannot delete individual characters.
# Sanfoundry Course Name course = "Python" # Deleting the string del course # Attempting to access the deleted string (will raise an error) # print(course) # NameError: name 'course' is not defined
Deleting Multiple Strings
You can delete multiple strings using del with multiple variables.
# Sanfoundry Topics topic1 = "Java" topic2 = "Python" # Deleting both topics del topic1, topic2 # Attempting to access deleted strings # print(topic1) # NameError # print(topic2) # NameError
Error:
NameError: name 'topic1' is not defined
Escape Characters in Python
Escape characters in Python allow you to include special characters in a string that are difficult or impossible to type directly. An escape sequence starts with a backslash (\) followed by a specific character to represent special symbols.
Common Escape Characters
| Escape Character | Description | Example Output |
|---|---|---|
| \’ | Single quote | Sanfoundry’s Quiz |
| \” | Double quote | “Python is fun” |
| \\ | Backslash | C:\path\file |
| \n | Newline | Adds a new line |
| \t | Tab space | Adds a tab space |
| \r | Carriage return | Moves cursor to the beginning |
| \b | Backspace | Removes previous character |
| \f | Form feed | Moves cursor to next page |
| \ooo | Octal value | Character with octal value |
| \xhh | Hex value | Character with hex value |
Example:
# Using Escape Characters print('Sanfoundry\'s Quiz') # Single quote print("He said, \"Learn Python!\"") # Double quote print("Path to file: C:\\path\\file") # Backslash print("Java\nQuiz") # Newline print("Python\tProgramming") # Tab space
Output:
Sanfoundry's Quiz
He said, "Learn Python!"
Path to file: C:\path\file
Java
Quiz
Python ProgrammingString Methods in Python
Python provides many built-in string methods to manipulate and process text. Here are some commonly used string methods:
| Method | Description | Example |
|---|---|---|
| lower() | Converts string to lowercase | “SANFOUNDRY”.lower() |
| upper() | Converts string to uppercase | “python”.upper() |
| strip() | Removes leading and trailing whitespaces | ” Java “.strip() |
| replace() | Replaces part of a string | “Java”.replace(“Java”, “Python”) |
| split() | Splits string into a list | “AI,ML,DBMS”.split(“,”) |
| join() | Joins elements of a list into a string | “, “.join([‘AI’, ‘ML’]) |
| find() | Finds position of a substring | “Sanfoundry”.find(“found”) |
| index() | Finds position, raises error if not found | “Sanfoundry”.index(“found”) |
| count() | Counts occurrences of a substring | “Python Python”.count(“Python”) |
| startswith() | Checks if string starts with a substring | “Machine”.startswith(“Mac”) |
| endswith() | Checks if string ends with a substring | “System”.endswith(“tem”) |
| capitalize() | Capitalizes the first character | “java”.capitalize() |
| title() | Converts string to title case | “data science”.title() |
| swapcase() | Swaps uppercase to lowercase and vice versa | “Python”.swapcase() |
| isalpha() | Checks if all characters are alphabets | “Python”.isalpha() |
| isdigit() | Checks if all characters are digits | “12345”.isdigit() |
| isalnum() | Checks if string is alphanumeric | “Python123”.isalnum() |
| isspace() | Checks if string contains only whitespaces | ” “.isspace() |
| zfill() | Pads string with zeros on the left | “42”.zfill(5) |
| format() | Formats string with placeholders | “Score: {}”.format(90) |
Example:
subj = " Python Programming " # 1. strip() - Removes leading and trailing whitespace print(subj.strip()) # Output: 'Python Programming' # 2. lower() - Converts all characters to lowercase print(subj.lower()) # Output: ' python programming ' # 3. upper() - Converts all characters to uppercase print(subj.upper()) # Output: ' PYTHON PROGRAMMING ' # 4. title() - Converts the first letter of each word to uppercase print(subj.title()) # Output: ' Python Programming ' # 5. replace() - Replaces occurrences of a substring print(subj.replace("Python", "Java")) # Output: ' Java Programming ' # 6. split() - Splits the string into a list print(subj.split()) # Output: ['Python', 'Programming'] # 7. join() - Joins elements of a list with a separator words = ["Hello", "World"] print(" ".join(words)) # Output: 'Hello World' # 8. find() - Finds the position of a substring print(subj.find("Programming")) # Output: 10 # 9. count() - Counts occurrences of a substring print(subj.count("o")) # Output: 2 # 10. startswith() - Checks if the string starts with a specific substring print(subj.startswith(" Python")) # Output: True # 11. endswith() - Checks if the string ends with a specific substring print(subj.endswith(" ")) # Output: True # 12. isalpha() - Checks if all characters are alphabetic (ignores spaces) print(subj.strip().isalpha()) # Output: False (because of space between words)
String Membership Testing in Python
String membership testing in Python checks whether a substring is present in a given string using the in and not in operators.
1. in Operator – Check if Substring is Present
Returns True if the substring is found.
# Sanfoundry Course Name course = "Python Programming" # Check if 'Python' is in the string print("Python" in course) # Output: True # Check if 'Java' is in the string print("Java" in course) # Output: False
2. not in Operator – Check if Substring is NOT Present
Returns True if the substring is not found.
# Sanfoundry Subject Name subject = "Data Science" # Check if 'AI' is not in the string print("AI" not in subject) # Output: True # Check if 'Data' is not in the string print("Data" not in subject) # Output: False
3. Case-Sensitive Membership Testing
# Sanfoundry Quiz Topic quiz = "Machine Learning" # Case-sensitive check print("machine" in quiz) # Output: False print("Machine" in quiz) # Output: True
Raw Strings in Python
Raw strings in Python are prefixed with r or R and treat backslashes (\) as literal characters. This is useful when dealing with file paths, regular expressions, or escape sequences where you want to avoid interpreting backslashes as escape characters.
# Normal string path_normal = "C:\\Users\\Sanfoundry\\Documents\\file.txt" print("Normal String:", path_normal) # Raw string path_raw = r"C:\Users\Sanfoundry\Documents\file.txt" print("Raw String:", path_raw)
Output:
Normal String: C:\Users\Sanfoundry\Documents\file.txt Raw String: C:\Users\Sanfoundry\Documents\file.txt
FAQs on Strings in Python
1. What is a string in Python?
A string in Python is a sequence of characters enclosed in single (‘ ‘), double (” “), or triple (”’ ”’ or “”” “””) quotes. It is used to store and manipulate text.
2. Are strings in Python mutable?
No, Python strings are immutable, meaning their content cannot be changed after creation. However, you can create a modified version of a string using slicing, concatenation, or string methods.
3. How can you access characters in a string?
Characters in a string can be accessed using indexing. The first character has an index of 0, and negative indices can be used to access characters from the end.
4. How do you concatenate two strings?
Strings can be combined using the + operator or the .join() method.
5. How do you repeat a string multiple times?
Using the * operator, a string can be repeated a specified number of times.
6. How do you format a string in Python?
Python provides multiple ways to format strings, including f-strings (f”…”), the .format() method, and the % formatting method.
7. How do you count the occurrences of a character in a string?
The .count() method is used to count how many times a specific character appears in a string.
Key Points to Remember
Here is the list of key points we need to remember about “Python Strings”.
- Strings can be created using single (‘ ‘), double (” “), or triple (”’ ”’ or “”” “””) quotes.
- Strings are immutable, meaning they cannot be modified directly.
- Indexing (text[0]) and slicing (text[1:4]) allow access to characters or substrings.
- Common string methods include upper(), lower(), replace(), strip(), and split().
- String formatting can be done using format(), f-strings (f”{var}”), and % operator.
- Escape characters like \n (newline) and \t (tab) enable special formatting.
- The join() method combines a list of strings into a single string.
- Raw strings (r””) treat backslashes as literal characters.