Python Strings

In Python, a string is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). Strings are one of the most widely used data types and are essential for storing and manipulating text in Python programs.

You can create a string easily as shown below:

message1 = 'Hello Python'
message2 = "Welcome to Programming"
message3 = '''This is
a multi-line
string'''

String Slicing

Slicing allows you to extract a portion (substring) from a string using the syntax [start:end:step]. Python strings are indexed, meaning every character has a position number. The first character starts at index 0.

text = "Python"
print(text[0])      # Output: P
print(text[1:4])    # Output: yth
print(text[:3])     # Output: Pyt
print(text[::2])    # Output: Pto
print(text[-1])     # Output: n
start β†’ Beginning index (default is 0)
end β†’ End index (excluded from result)
step β†’ Optional step size (default is 1)

Negative indices can be used to access characters from the end of the string.

String Methods

Python provides numerous built-in string methods for text manipulation. These methods do not modify the original string; instead, they return a new one.

Method Description Example
upper() Converts all characters to uppercase "python".upper() β†’ "PYTHON"
lower() Converts all characters to lowercase "PYTHON".lower() β†’ "python"
title() Capitalizes the first letter of each word "hello world".title() β†’ "Hello World"
capitalize() Capitalizes the first character "python".capitalize() β†’ "Python"
strip() Removes leading and trailing spaces " hello ".strip() β†’ "hello"
replace() Replaces a substring with another "I like Java".replace("Java", "Python") β†’ "I like Python"
split() Splits the string into a list "a,b,c".split(",") β†’ ['a', 'b', 'c']
join() Joins elements of a list into one string " ".join(['I', 'love', 'Python']) β†’ "I love Python"
find() Returns index of a substring (-1 if not found) "Python".find("th") β†’ 2
count() Counts occurrences of a substring "banana".count("a") β†’ 3

String Immutability

Strings in Python are immutable, meaning their content cannot be changed after creation. If you try to modify a string, Python will throw an error.

text = "Python"
text[0] = "J"      # Error
Instead, you must create a new string:

new_text = "J" + text[1:]
print(new_text)     # Output: Jython
So, every operation like replace(), upper(), or lower() actually returns a new string without altering the original.

Escape Sequences

Escape sequences allow you to include special characters or formatting inside strings. They start with a backslash ().

Escape Sequence Meaning Example Output
\n New line "Hello\nWorld" β†’
Hello
World
\t Tab space "Python\tLanguage" β†’ Python Language
\\ Backslash "C:\\path\\file.txt" β†’ C:\path\file.txt
\' Single quote 'It\'s Python' β†’ It's Python
\" Double quote "He said \"Hi\"" β†’ He said "Hi"
Triple-quoted strings can also be used for multi-line text without needing escape characters.

String Formatting

Python provides multiple ways to format strings dynamically β€” i.e., insert variables or expressions into strings.

1. f-strings (Python 3.6+)

This is the most modern and efficient way to format strings.

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
You can even include expressions:

print(f"Next year, I will be {age + 1} years old.")

2. format() Method

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
print("My name is {0} and I am {1}.".format(name, age))

3. % Formatting (Older style)

name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))

Summary

Strings are the foundation of text processing in Python. Understanding how to manipulate and format them effectively will make your programs more readable, dynamic, and user-friendly.

Concept Description
String Sequence of characters enclosed in quotes
Slicing Extracts specific portions of a string
String Methods Built-in functions for text manipulation
Immutability Strings cannot be changed once created
Escape Sequences Used to include special characters like \n and \t
String Formatting Combines variables and text dynamically
In the next article, we'll explore Lists in Python β€” one of the most powerful and flexible data structures used to store and manage collections of data.
Share this Article