Python Strings
A string in Python is a sequence of characters used to represent text. Strings can be written using either single quotes (' ') or double quotes (" ")—both work exactly the same way.
Displaying a String
You can show text on the screen using the print() function.
Example:
Using Quotes Inside a String
You can include quotation marks inside a string as long as they are different from the quotes used to define the string.
Example:
Assigning a String to a Variable
Strings are commonly stored in variables so they can be reused later in a program.
Example:
Multi-Line Strings
Python allows you to store text across multiple lines using triple quotes (""" """ or ''' '''). Line breaks in the code are preserved in the output.
Example (Triple Double Quotes):
Example (Triple Single Quotes):
Strings as Sequences
In Python, strings behave like sequences (arrays) of Unicode characters. Each character has a position index, starting from 0.
Example:
This prints the character at index position 2.
Looping Through a String
Since strings are iterable, you can loop through each character using a for loop.
Example:
This prints each character on a new line.
Finding the Length of a String
Use the len() function to determine how many characters a string contains.
Example:
Checking for Text Inside a String
You can check whether a word or character exists in a string using the in keyword.
Example:
Using in with an if Statement
You can combine the in keyword with conditional statements to perform checks.
Example:
Checking if Text Is NOT Present
To verify that a word or character does not exist in a string, use the not in keyword.
Example:
Using not in with an if Statement
Example:
Python String Slicing
String slicing allows you to extract a specific portion of a string by selecting a range of characters. This is done using square brackets [] with a start index and an end index, separated by a colon.
• The start index is inclusive, and the end index is exclusive.
• String indexing always begins at 0.
Basic Slice Syntax
Example:
This extracts characters starting from index 3 up to, but not including, index 7.
Slicing From the Beginning
If you omit the starting index, Python automatically begins slicing from the first character.
Example:
This returns the characters from the start of the string up to index 4.
Slicing Until the End
If you leave out the ending index, Python slices the string all the way to the last character.
Example:
This extracts everything from index 6 to the end of the string.
Using Negative Indexes
Negative indexing allows you to count characters from the end of the string.
• -1 refers to the last character
• -2 refers to the second-last character, and so on
Example:
This extracts characters starting from the 7th position from the end up to (but not including) the 3rd position from the end.
Modifying Strings in Python
Python provides many built-in methods that allow you to change or manipulate string values easily. These methods do not modify the original string—instead, they return a new modified string.
Converting Text to Uppercase
The upper() method converts all characters in a string to capital letters.
Example:
Converting Text to Lowercase
The lower() method changes all characters in a string to lowercase letters.
Example:
Removing Extra Spaces
Sometimes strings contain unwanted spaces at the beginning or end. The strip() method removes these extra spaces.
Example:
This is especially useful when working with user input.
Replacing Part of a String
The replace() method allows you to substitute one part of a string with another.
Example:
Splitting a String into a List
The split() method divides a string into a list based on a specified separator.
Example:
This is useful when processing CSV data, user input, or file content.
Combining Strings in Python
In Python, string concatenation means joining two or more strings into a single string. This is commonly done using the + operator.
Joining Two Strings
The + operator connects strings in the order they appear.
Example:
Adding Space Between Strings
When joining words, you often need to include a space manually
Example:
Concatenating Multiple Strings
You can also combine more than two strings at once.
Example:
Important Notes
• Only strings can be concatenated using +
• Numbers must be converted to strings before concatenation
• For advanced formatting, Python also provides f-strings and format()
Python – String Formatting
In Python, strings and numbers cannot be directly joined using the + operator. Attempting to do so will raise a TypeError because Python treats text and numeric values as different data types.
Incorrect Example:
To safely combine text with numbers, Python provides string formatting techniques such as f-strings and the format() method.
Using F-Strings (Recommended)
F-strings (formatted string literals) were introduced in Python 3.6 and are now the most efficient and readable way to format strings.
To create an f-string:
• Prefix the string with f
• Place variables or expressions inside {}
Basic F-String Example
Placeholders in F-Strings
The expressions inside {} are called placeholders. They can include:
• Variables
• Mathematical expressions
• Function calls
• Formatting rules
Using Variables Inside Placeholders
Formatting Values with Modifiers
You can control how values appear using format specifiers.
A format modifier is added after a colon : inside the placeholder.
Formatting Floating-Point Numbers
✔ .1f → rounds the value to 1 decimal place
Using Expressions Inside F-Strings
F-strings can evaluate Python expressions directly.
Example:
Key Benefits of F-Strings
• Cleaner and more readable syntax
• Faster execution compared to older methods
• Supports inline calculations and formatting
• Ideal for real-world applications and APIs
Python – Escape Characters
Escape characters are special sequences used in Python strings to represent characters that cannot be typed directly or would otherwise break the string syntax.
An escape sequence always begins with a backslash (\), followed by a character that has a predefined meaning.
Why Escape Characters Are Needed
Some characters—such as quotes, new lines, or tabs—have special meanings in Python. If you try to use them directly inside a string, Python may throw a syntax error or interpret them incorrectly.
Problem Example (Without Escape Characters)
❌ This causes an error because the string ends before expected.
Using Escape Characters Correctly
You can safely include special characters by prefixing them with a backslash.
Correct Example
Output:
Commonly Used Escape Characters
Single Quote (\')
Backslash (\\)
New Line (\n)
Tab Space (\t)
Carriage Return (\r)
Backspace (\b)