1. What is a String?
- A string is a sequence of characters enclosed in quotes.
- Strings are immutable, meaning their contents cannot be changed after creation.
- Python supports single quotes (
'), double quotes ("), and triple quotes ('''or""") for defining strings.
2. String Operations
1. Concatenation
- Combining two or more strings using the
+operator.
2. Repetition
- Repeating a string using the
*operator.
3. Indexing
- Accessing individual characters in a string using their index.
- Python uses zero-based indexing (the first character has index
0).
4. Slicing
- Extracting a substring using a range of indices.
- Syntax:
string[start:stop:step]
5. Length
- Finding the length of a string using the
len()function.
3. String Methods
1. upper() and lower()
- Convert a string to uppercase or lowercase.
2. strip(), lstrip(), and rstrip()
- Remove leading and trailing whitespace (or specified characters).
3. replace()
- Replace a substring with another substring.
4. split()
- Split a string into a list of substrings based on a delimiter.
5. join()
- Join a list of strings into a single string using a delimiter.
6. find() and index()
- Find the index of a substring in a string.
find()returns-1if the substring is not found, whileindex()raises an error.
7. startswith() and endswith()
- Check if a string starts or ends with a specific substring.
8. isalpha(), isdigit(), isalnum()
- Check if all characters in a string are alphabetic, numeric, or alphanumeric.
4. String Formatting
1. f-strings (Python 3.6+)
- Embed expressions inside string literals using
{}.
2. format() Method
- Insert values into a string using placeholders
{}.
3. % Formatting (Older Style)
- Use
%as a placeholder for values.
5. Escape Sequences
- Special characters used to represent non-printable or special characters in strings.
- Common escape sequences:
\n: Newline\t: Tab\\: Backslash\": Double quote\': Single quote
6. Additional Examples
-
Concatenation:
-
Slicing:
-
String Methods:
-
String Formatting:
7. Best Practices
- Use
f-stringsfor string formatting (Python 3.6+). - Use triple quotes for multi-line strings.
- Avoid using
+for concatenating many strings (usejoin()instead for efficiency).