Strings in Python:
In Python, a string is a sequence of characters enclosed within single quotes ('), double quotes
("), or triple quotes (''' ''' or """ """) for multiline strings. Strings are immutable, meaning once
created, they cannot be changed.
Basic String Creation
Syntax
# Single-quoted string
str1 = 'Hello, World!'
# Double-quoted string
str2 = "Python is fun!"
# Triple-quoted string (can span multiple lines)
str3 = '''This is a
multiline string'''
# Empty string
str4 = ""
Using backslash(' \') to escape quotes, \n ,using r before a string:
In Python, special characters like \ can be used within strings for various purposes, such as
escaping quotes, adding new lines, and formatting paths. Let's go over some of these:
1. Escaping Quotes with Backslash (\)
If you want to include single or double quotes inside a string without ending the string, you
can use the backslash (\) to "escape" them.
Using backslash to escape double quotes
text = "He said, \"Hello, World!\""
print(text)
Using backslash to escape single quotes
text = 'It\'s a beautiful day!'
print(text)
Output:
He said, "Hello, World!"
It's a beautiful day!
2. Newline Character (\n)
The \n character is used to create a newline in a string, which means it will move any text
after it to the next line.
text = "Hello, World!\nWelcome to Python programming."
print(text)
Output:
Hello, World!
Welcome to Python programming.
3. Raw Strings with r
Prefixing a string with r (or R) makes it a raw string. This tells Python to treat backslashes as
literal characters, so escape sequences like \n are not processed. This is especially useful for
file paths, regular expressions, or strings where you don’t want special characters to be
interpreted.
# Without raw string (backslashes act as escape characters)
path = "C:\\Users\\newfolder\\test.txt"
print(path)
# Using raw string
raw_path = r"C:\Users\newfolder\test.txt"
print(raw_path)
Output:
C:\Users\newfolder\test.txt
C:\Users\newfolder\test.txt
String Concatenation (`+`):
In Python, the `+` operator is used to concatenate (combine) two or more strings into a single
string.
first_name = "Alice"
last_name = "Johnson"
full_name = first_name + " " + last_name
print(full_name)
Output: Alice Johnson
This is useful when you want to combine strings with variables, spaces, or punctuation.
String Repetition (`*`):
The `*` operator can be used to repeat a string a specified number of times.
greeting = "Hello! "
repeated_greeting = greeting * 3
print(repeated_greeting)
Output: Hello! Hello! Hello!
String repetition is helpful for creating simple patterns or emphasizing text.
Automatic Concatenation (Adjacent Strings):
In Python, strings placed next to each other are automatically concatenated, even without `+`.
This is particularly useful for long strings or multiline strings, where you can break them into
parts for readability.
long_text = ("This is an example of "
"automatic concatenation "
"in Python.")
print(long_text)
Output: This is an example of automatic concatenation in Python.
Automatic concatenation works in parentheses, brackets, or braces. However, without them, a
‘SyntaxError’ will occur.
Examples of Usage - Practical Examples:
1. Concatenating User Input:
first = input("Enter your first name: ")
last = input("Enter your last name: ")
print("Full Name: " + first + " " + last)
2. Simple Pattern Creation:
pattern = "* " * 5
print(pattern)
3. Breaking Long Strings for Readability:
message = (
"Welcome to Python programming! "
"This is an example of how "
"you can make your code more readable."
)
print(message)
Accessing Characters in a String
You can access specific characters in a string using indexing.
Syntax
str = "Hello"
print(str[0]) # H
print(str[1]) # e
Example:
word = "Python"
print("First character:", word[0]) # Output: P
print("Last character:", word[-1]) # Output: n
String Slicing:
Slicing allows you to extract a part of the string.
Syntax: str[start:end:step]
start: Starting index (inclusive)
end: Ending index (exclusive)
step: Step size for slicing
Example:
text = "Hello, World!"
print(text[0:5]) # Output: Hello
print(text[7:12]) # Output: World
print(text[::-1]) # Output: !dlroW ,olleH (reversed string)
Common String Methods:
1. len(): Get length of a string.
text = "Python"
print(len(text)) # Output: 6
2. str.lower(): Convert to lowercase.
print("HELLO".lower()) # Output: hello
3. str.upper(): Convert to uppercase.
print("hello".upper()) # Output: HELLO
4. str.strip(): Remove whitespace from the start and end.
text = " Python "
print(text.strip()) # Output: Python
5. str.replace(old, new): Replace substring.
text = "Hello, World!"
print(text.replace("World", "Python")) # Output: Hello, Python!
6. str.find(sub): Find the position of a substring.
text = "Hello, World!"
print(text.find("World")) # Output: 7
7. str.split(delimiter): Split string into a list.
text = "apple,banana,grape"
fruits = text.split(",")
print(fruits) # Output: ['apple', 'banana', 'grape']
8. str.join(iterable): Join elements of an iterable into a single string.
fruits = ['apple', 'banana', 'grape']
print(", ".join(fruits)) # Output: apple, banana, grape
9. str.startswith(prefix) and str.endswith(suffix): Check if a string starts or ends with a
specific substring.
text = "Python programming"
print(text.startswith("Python")) # Output: True
print(text.endswith("programming")) # Output: True
String Formatting:
In Python, string formatting is the process of creating strings by embedding or substituting
values into them, which allows for more readable and dynamic string construction. Python
provides multiple ways to format strings:
1. Old-style (%) Formatting: The old-style `%` formatting uses placeholders within the
string and `%` symbols to substitute values.
name = "Alice"
age = 30
message = "Hello, %s! You are %d years old." % (name, age)
print(message)
Output: Hello, Alice! You are 30 years old.
Placeholders:
- `%s`: string
- `%d`: integer
- `%f`: float (use `%.2f` for two decimal places)
2. str.format() Method:
This method uses `{}` as placeholders and substitutes values by calling `.format()` on the
string.
name = "Alice"
age = 30
message = "Hello, {}! You are {} years old.".format(name, age)
Output: Hello, Alice! You are 30 years old. You can also specify positions within `{}` for
reordering:
message = "You are {1} years old, {0}.".
format (name, age)
print(message)
Output: You are 30 years old, Alice.
3. f-Strings (Formatted String Literals)
Introduced in Python 3.6, f-strings allow for directly embedding expressions inside `{}` by
prefixing the string with `f`.
name = "Alice"
age = 30
message = f"Hello, {name}! You are {age} years old."
print(message)
Output: Hello, Alice! You are 30 years old.
message = f"In five years, {name} will be {age + 5} years old."
print(message)
Output: In five years, Alice will be 35 years old.
4. string.Template Class:
The `string` module provides a `Template` class for simpler substitutions, where placeholders
are defined with `$`.
from string import Template
template = Template("Hello, $name! You are $age years old.")
message = template.substitute(name="Alice", age=30)
print(message)
Output: Hello, Alice! You are 30 years old.
Use Cases of String Formatting:
Dynamic messages, in applications based on user input or data.
Logging and debugging, where variable values are embedded within messages.
Displaying data, in a formatted way, such as currency, dates, or rounded decimals.
Summary:
Each formatting style has its strengths:
- `%` formatting is an older but still usable method.
- `str.format()` offers more flexibility and is more readable.
- f-strings are concise and powerful, making them the preferred method in modern Python.
- `Template` is simple and suitable for cases with predefined strings and minimal logic.