Skip to main content

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.
Examples:

2. String Operations

1. Concatenation

  • Combining two or more strings using the + operator.
Example:

2. Repetition

  • Repeating a string using the * operator.
Example:

3. Indexing

  • Accessing individual characters in a string using their index.
  • Python uses zero-based indexing (the first character has index 0).
Example:

4. Slicing

  • Extracting a substring using a range of indices.
  • Syntax: string[start:stop:step]
Examples:

5. Length

  • Finding the length of a string using the len() function.
Example:

3. String Methods

1. upper() and lower()

  • Convert a string to uppercase or lowercase.
Example:

2. strip(), lstrip(), and rstrip()

  • Remove leading and trailing whitespace (or specified characters).
Example:

3. replace()

  • Replace a substring with another substring.
Example:

4. split()

  • Split a string into a list of substrings based on a delimiter.
Example:

5. join()

  • Join a list of strings into a single string using a delimiter.
Example:

6. find() and index()

  • Find the index of a substring in a string.
  • find() returns -1 if the substring is not found, while index() raises an error.
Example:

7. startswith() and endswith()

  • Check if a string starts or ends with a specific substring.
Example:

8. isalpha(), isdigit(), isalnum()

  • Check if all characters in a string are alphabetic, numeric, or alphanumeric.
Example:

4. String Formatting

1. f-strings (Python 3.6+)

  • Embed expressions inside string literals using {}.
Example:

2. format() Method

  • Insert values into a string using placeholders {}.
Example:

3. % Formatting (Older Style)

  • Use % as a placeholder for values.
Example:

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
Example:

6. Additional Examples

  • Concatenation:
  • Slicing:
  • String Methods:
  • String Formatting:

7. Best Practices

  • Use f-strings for string formatting (Python 3.6+).
  • Use triple quotes for multi-line strings.
  • Avoid using + for concatenating many strings (use join() instead for efficiency).