Python Strings
In Python, strings are sequences of characters enclosed in either single quotes ('), double quotes ("), or triple quotes (''' or """). Strings are widely used to store and manipulate textual data.
1. Creating Strings
You can create a string by assigning characters to a variable using quotes:
Examples:
# Using single quotes
s1 = 'Hello'
# Using double quotes
s2 = "World"
# Using triple quotes for multiline strings
s3 = '''This is
a multiline
string'''
s4 = """This is another
multiline string"""
2. String Indexing and Slicing
Python strings are indexed arrays, where each character is assigned a position starting from 0 for the first character. You can access characters from a string using square brackets [].
Example:
text = "Python"
# Accessing single characters
print(text[0]) # Output: P
print(text[3]) # Output: h
# Negative indexing (from the end)
print(text[-1]) # Output: n (last character)
print(text[-3]) # Output: t (third-last character)
You can also extract a portion of a string (substring) using slicing:
Example:
text = "Python Programming"
# Slicing (start:stop:step)
print(text[0:6]) # Output: Python
print(text[7:]) # Output: Programming (from index 7 to the end)
print(text[:6]) # Output: Python (up to but not including index 6)
3. String Concatenation
You can concatenate (join) two or more strings using the + operator.
Example:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
4. String Repetition
You can repeat strings using the * operator.
Example:
str1 = "Hello"
print(str1 * 3) # Output: HelloHelloHello
5. Escape Characters
Escape characters are special characters that allow you to include characters that are otherwise hard to include in a string (like newlines, tabs, or quotes). Escape sequences start with a backslash \.
| Escape Character | Description | Example |
|---|---|---|
\' | Single quote | 'It\'s a book' |
\" | Double quote | "He said \"Hi\"" |
\\ | Backslash | "This is a backslash: \\ " |
\n | Newline | "Line1\nLine2" |
\t | Tab | "Hello\tWorld" |
Example:
text = 'It\'s a beautiful day'
print(text) # Output: It's a beautiful day
text = "Hello\nWorld"
print(text) # Output:
# Hello
# World
6. String Methods
Python provides a variety of built-in methods for working with strings. Here are some common string methods:
| Method | Description | Example |
|---|---|---|
upper() | Converts all characters to uppercase | "hello".upper() → "HELLO" |
lower() | Converts all characters to lowercase | "HELLO".lower() → "hello" |
strip() | Removes leading and trailing whitespace | " hello ".strip() → "hello" |
replace(old, new) | Replaces occurrences of a substring with another string | "hello".replace("l", "z") → "hezzo" |
split(separator) | Splits the string into a list of substrings | "a,b,c".split(",") → ["a", "b", "c"] |
join(iterable) | Joins elements of a list into a string | ",".join(["a", "b", "c"]) → "a,b,c" |
find(substring) | Returns the index of the first occurrence of the substring | "hello".find("l") → 2 |
len() | Returns the length of the string | len("hello") → 5 |
Example:
text = " Python Programming "
# Converting to uppercase
print(text.upper()) # Output: " PYTHON PROGRAMMING "
# Removing spaces from the start and end
print(text.strip()) # Output: "Python Programming"
# Replacing a word
print(text.replace("Python", "Java")) # Output: " Java Programming "
# Splitting the string into a list of words
words = text.strip().split()
print(words) # Output: ['Python', 'Programming']
# Joining a list of words into a string
joined_text = " ".join(words)
print(joined_text) # Output: "Python Programming"
7. String Formatting
Python provides multiple ways to format strings dynamically by embedding variables or expressions into the string.
a. f-Strings (Python 3.6+)
f-strings allow you to embed expressions inside string literals, using curly braces {}.
Example:
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message) # Output: My name is Alice and I am 25 years old.
b. format() Method
The format() method can also be used to insert variables into strings.
Example:
name = "Bob"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
print(message) # Output: My name is Bob and I am 30 years old.
c. Old-style Formatting (%)
This method uses % to substitute values into a string. Though it’s less common now, it’s still supported.
Example:
name = "Charlie"
age = 35
message = "My name is %s and I am %d years old." % (name, age)
print(message) # Output: My name is Charlie and I am 35 years old.
8. String Immutability
Strings in Python are immutable, which means that once a string is created, it cannot be changed. Any operation that seems to modify a string actually returns a new string.
Example:
text = "Hello"
text[0] = 'h' # This will cause an error because strings are immutable
To “modify” a string, you need to create a new one:
Example:
text = "Hello"
new_text = "h" + text[1:] # Create a new string with the desired modification
print(new_text) # Output: "hello"
9. Checking Substrings
You can check if a substring exists within a string using the in keyword.
Example:
text = "Python Programming"
print("Python" in text) # Output: True
print("Java" in text) # Output: False
10. Multiline Strings
Multiline strings can be created using triple quotes (''' or """).
Example:
text = '''This is a
multiline
string'''
print(text)
# Output:
# This is a
# multiline
# string
Summary:
- Strings are sequences of characters and are immutable.
- You can access and slice strings using indexing.
- Use
+for concatenation and*for repetition. - Escape characters, such as
\n(newline), allow for special formatting within strings. - There are various string methods like
upper(),lower(),split(),replace(), etc. - String formatting using f-strings,
format(), and%allows for dynamic string content.