The usage of str in Python
In Python, str is a data type for storing strings. Here are some common usages of str:
- Create a string.
- my_str = “Hello, World!” # Create a string using double quotes
- Concatenating strings
- result = str1 + str2 # Concatenation of strings
- String indexing and slicing:
- my_str = “Hello, World!”
print(my_str[0]) # Output the first character ‘H’
print(my_str[7:12]) # Output the slice ‘World’ - Length of the string:
- my_str = “Hello, World!”
length = len(my_str) # Determine the length of the string - Commonly used methods for strings:
- 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!’] - Format the string:
- “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.