The usage of str in Python

In Python, str is a data type for storing strings. Here are some common usages of str:

  1. Create a string.
  2. my_str = “Hello, World!” # Create a string using double quotes
  3. Concatenating strings
  4. result = str1 + str2 # Concatenation of strings
  5. String indexing and slicing:
  6. my_str = “Hello, World!”
    print(my_str[0]) # Output the first character ‘H’
    print(my_str[7:12]) # Output the slice ‘World’
  7. Length of the string:
  8. my_str = “Hello, World!”
    length = len(my_str) # Determine the length of the string
  9. Commonly used methods for strings:
  10. my_string = “Hello, World!”
    print(my_string.upper()) # convert the string to uppercase ‘HELLO, WORLD!’
    print(my_string.lower()) # convert the string to lowercase ‘hello, world!’
    print(my_string.replace(“Hello”, “Hi”)) # replace the specified substring in the string ‘Hi, World!’
    print(my_string.split(“,”)) # split the string by specified delimiter into a list [‘Hello’, ‘ World!’]
  11. Format the string:
  12. “I’m Alice and I’m 25 years old.”

These are just some common uses of str, there are many more methods and functionalities that can be utilized.

bannerAds