What is Strings?

A string is a data type that stores a sequence of characters.

  1. Creating a String: You can create a string by enclosing text in single (') or double (") quotes.

    name = "Tarif"
    greeting = 'Moshi Moshi'
    
  2. Multiline Strings: Use triple quotes (''' or """) to create strings that span multiple lines.

    message = """This is a
    multiline string."""
    
  3. Next Line: By using \\n we can go to the next line.

    text = ("Tarif is a good boy.\\nTarif is learning Python.")
    
    #Output -- 
    
    Tarif is a good boy.
    Tarif is learning Python.
    
  4. Concatenation: You can combine strings using the + operator.

    full_name = "Md"
    second_name = "Tarif"
    print(full_name + second_name)
    
    # Output:
    MdTarif
    
  5. Length: Use the len() function to get the length of a string.

    name = "Tarif"
    print(len(name))
    
    # Output: 5
    
  6. Indexing: You can access characters in a string using an index, with the first character at index 0.

    word = "Python"
    print(word[0])
    # Output: 'P'
    
    print(word[-1])
    # Output: 'n' (negative index starts from the end)
    
  7. Slicing: You can get a substring by slicing the string.

    P y t h o n
    0 1 2 3 4 5
    
    word = "Python"
    
    print(word[0:2])  # Output: 'Py'
    print(word[2:])   # Output: 'thon'
    print(word[:])    # Output: 'Python'
    
  8. In function: It checks whether the word is in the sentence or not.

    my_food = "I like pizza and pasta"
    result = 'salad' in my_food        # Output: False
    
    my_food = "samosa, jalebi"
    answer = 'apple' not in my_food    # Output: True
    
  9. Replace: It is used to replace occurrences of a substring within a string with another substring.

    text = "I like apples"
    ans = text.replace("apples", "bananas")
    
    print(ans)  # Output: "I like bananas"