Python Strings
A string in Python is a sequence of characters enclosed in single, double, or triple quotes. Strings are one of the most widely used data types in Python, representing text data.
What is a String?
A string is a collection of characters enclosed within quotes. Python provides several ways to define and manipulate strings. Strings are immutable, meaning that once created, they cannot be altered.
Creating a String
Strings in Python can be created by enclosing characters in either single quotes ('
) or double quotes ("
).
Syntax
# Creating strings in Python
str1 = 'Hello, World!' # Single quotes
str2 = "Python is awesome" # Double quotes
str3 = '''This is a
multi-line string''' # Triple quotes for multi-line strings
Explanation:
Here, str1
, str2
, and str3
are examples of strings created with single quotes, double quotes, and triple quotes, respectively. Triple quotes are especially useful for multi-line strings.
String Indexing and Slicing
Strings in Python are indexed, meaning each character in a string has a corresponding index number. The index starts from 0 for the first character. Negative indexing can also be used to access characters from the end of the string.
Indexing Syntax
Syntax
# Indexing and Slicing a string
str = "Python"
first_char = str[0] # Access first character (P)
last_char = str[-1] # Access last character (n)
substring = str[1:4] # Access substring (yt)
Explanation:
In the above example:str[0]
accesses the first characterP
.str[-1]
accesses the last charactern
.str[1:4]
slices the string from index 1 to 3, returningyt
.
String Concatenation
String concatenation in Python can be done using the +
operator. This operator joins two or more strings together.
Syntax
# Concatenating strings in Python
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Concatenates two strings with a space
Explanation:
Here, str1 + " " + str2
concatenates the two strings str1
and str2
, adding a space between them. The result will be the string "Hello World"
.
String Methods
Python provides several built-in methods to perform common operations on strings. These methods allow us to manipulate strings efficiently. Below are some common string methods:
Example Methods
str = "Python Programming"
upper_case = str.upper() # Converts to uppercase
lower_case = str.lower() # Converts to lowercase
count_python = str.count("Python") # Counts occurrences of 'Python'
replace_programming = str.replace("Programming", "Coding") # Replace 'Programming' with 'Coding'
split_words = str.split() # Splits the string into a list of words
Explanation:
In the above example:
str.upper()
converts the string to uppercase.str.lower()
converts the string to lowercase.str.count("Python")
counts how many times the word "Python" appears in the string.str.replace("Programming", "Coding")
replaces "Programming" with "Coding".str.split()
splits the string into a list of words, using spaces as delimiters.
String Escape Characters
Python allows you to use special characters in strings called escape characters. These characters are preceded by a backslash () and serve various purposes, such as inserting new lines, tabs, or quotes inside strings.
Common Escape Characters:
n
: Newlinet
: Tab'
: Single quote"
: Double quote: Backslash
Escape Characters Example
# Escape characters in Python strings
str1 = "HellonWorld" # New line between Hello and World
str2 = "PythontProgramming" # Tab between Python and Programming
str3 = "He said, "Python is awesome!"" # Double quotes inside string
str4 = "This is a backslash: " # Display a backslash
Explanation:
In the example above:n
creates a new line between "Hello" and "World".t
adds a tab between "Python" and "Programming"."
allows double quotes to appear inside the string.displays a backslash.
String Formatting
String formatting allows you to embed variables into a string. Python provides several ways to format strings, such as using the %
operator, str.format()
method, and f-strings (formatted string literals).
Example Using % Operator
# Using % operator for string formatting
name = "Alice"
age = 25
message = "Hello, %s! You are %d years old." % (name, age)
Explanation:
The%s
and %d
are placeholders for a string and an integer, respectively. The values of name
and age
are inserted into the string in their respective positions.
Example Using str.format()
# Using str.format() for string formatting
message = "Hello, {}! You are {} years old.".format(name, age)
Explanation:
The{}
placeholders are replaced with the values passed to the format()
method.
Example Using f-strings
# Using f-strings for string formatting
message = f"Hello, {name}! You are {age} years old."
Explanation:
f-strings (formatted string literals) are a concise way to embed expressions inside string literals. They are prefixed with the letter f
and expressions are enclosed in curly braces {}
.