String Manipulation in python

 1. Basic String Creation and Assignment

  • Single Quotes: my_string = 'Hello, World!'
  • Double Quotes: my_string = "Hello, World!"
  • Triple Quotes: Useful for multi-line strings or strings containing both single and double quotes. 



  • 2. Accessing Characters in Strings
        Strings in Python are sequences of characters, so you can access individual characters using indexing:

    3. String Slicing
        Slicing allows you to extract a substring from a string:
        


    4. String Length

        Use len() to get the number of characters in a string.

    5. String Concatenation and Repetition
        Concatenation: Using + to join strings together.

        Repetition: Using * to repeat strings.

    6. Common String Methods
        
    a) Changing Case
        
    .upper(): Converts all characters to uppercase.
    .lower(): Converts all characters to lowercase.

    .title(): Capitalizes the first letter of each word.

    b) Trimming Whitespace
        
    .strip(): Removes leading and trailing whitespace.

    .lstrip() and .rstrip(): Remove whitespace from the left or right, respectively.

    c) Replacing Text
        
    .replace(old, new): Replaces occurrences of a substring with a new substring.

    d) Splitting and Joining
    .split(separator): Splits a string into a list of substrings based on a separator.

    .join(iterable): Joins elements of an iterable (like a list) into a string with a specified
    separator.



    7. Checking for Substrings


    in: Checks if a substring exists within a string.


    .startswith() and .endswith(): Check if a string starts or ends with a specified substring.


    8. Finding Substrings

        .find(substring): Returns the index of the first occurrence of a substring, or -1 if not
    found.
    .count(substring): Counts the occurrences of a substring within a string.

    9. Formatting Strings

        F-strings (formatted string literals) in Python 3.6+:


    .format() method:

    Percent formatting (older style):

    10. Escape Characters
        Use escape characters to include special characters in strings:
    • \' – single quote
    • \" – double quote
    • \\ – backslash
    • \n – newline
    • \t – tab

    11. Advanced Techniques
        a) String Reversal
    Strings can be reversed by slicing.

    b) Using Regular Expressions (regex)
        
  • The re module in Python allows for advanced pattern matching.
  • Example: Find all occurrences of a pattern.


  • c) String Encoding and Decoding

        Strings can be encoded into bytes and decoded back.


    No comments:

    Post a Comment