What are common string operations?

0114

Common string operations in Python include:

  1. Concatenation: Joining two or more strings together.

    full_name = "John" + " " + "Doe"  # "John Doe"
  2. Repetition: Repeating a string multiple times.

    echo = "Hello " * 3  # "Hello Hello Hello "
  3. Length: Getting the number of characters in a string.

    length = len(full_name)  # 8
  4. Indexing: Accessing individual characters using their position.

    first_char = full_name[0]  # 'J'
    last_char = full_name[-1]   # 'e'
  5. Slicing: Extracting a substring from a string.

    substring = full_name[0:4]  # "John"
  6. Changing Case: Converting strings to upper or lower case.

    upper_case = full_name.upper()  # "JOHN DOE"
    lower_case = full_name.lower()  # "john doe"
  7. Finding Substrings: Checking if a substring exists within a string.

    index = full_name.find("Doe")  # 5
  8. Replacing Substrings: Replacing parts of a string with another string.

    new_name = full_name.replace("Doe", "Smith")  # "John Smith"

These operations are essential for manipulating and processing text data in Python. If you want to practice these operations, consider exploring related labs on LabEx!

0 Comments

no data
Be the first to share your comment!