Strings in Python
Quotes: Single, Double, and Triple
A string in Python can be enclosed in single ('), double ("), or triple quotes (''' or """). Triple quotes are typically used for multi-line strings.
Example:
Output:
Length of Strings
Use the len() function to determine the length of a string.
Example:
Operations on Strings
- Concatenation: Using the
+operator.
- Replication: Using the
*operator to repeat a string.
- Comparison: Using
==,>,<operators for lexicographic comparisons.
Escape Characters
The backslash (\) is used to introduce special characters.
\nfor newline\tfor tab\'for escaping single quotes
Example:
Output:
Substrings
The in keyword checks if a string is a substring of another.
Example:
Indexing and Slicing
Strings support both positive and negative indexing. The first character has index 0, and the last has index -1.
Example:
Slicing: To extract a portion of a string.
Immutability of Strings
Strings are immutable in Python, meaning their contents cannot be changed once created.
Example:
String Methods
capitalize(): Capitalizes the first letter.isalpha(): Checks if all characters are alphabetic.
Example: