How to use str in Python?
In Python, str is a built-in data type that is used for creating and manipulating strings.
To create a string:
You can use either single or double quotation marks to create a string, as shown below:
str1 = 'Hello'
str2 = "World"
Strings can contain any characters, including letters, numbers, special characters, etc.
Operations on Strings:
In Python, strings are immutable, meaning once a string is created, its value cannot be changed. However, new strings can be created through various operations.
- String concatenation:
You can use the plus operator (+) to concatenate strings, as shown below:
str3 = str1 + str2
print(str3) # 输出:HelloWorld
- String indexing and slicing:
You can use indexing to access individual characters in a string, where the index starts at 0, as shown below:
print(str1[0]) # 输出:H
You can use slicing to obtain a part of a string. The syntax for slicing is [start:end:step], where start is the starting index, end is the ending index (not inclusive), and step is the increment. By default, step is set to 1. For example:
print(str1[1:4]) # 输出:ell
- Length of string:
You can use the len function to obtain the length of a string, as shown below:
print(len(str1)) # 输出:5
- String formatting:
You can format a string using the format method, as shown below:
name = 'Alice'
age = 25
print("My name is {}, and I am {} years old.".format(name, age))
# 输出:My name is Alice, and I am 25 years old.
- Other common actions:
- Check whether a string contains a certain substring by using the ‘in’ keyword, like ‘l’ in str1.
- Changing the case of a string: use the upper method to convert the string to uppercase, and use the lower method to convert the string to lowercase.
- To remove spaces from both ends of a string, use the strip method.
- Find the position of a substring in a string: use either the find method or the index method.
- Replace a substring: Use the replace method.
This is only a part of string manipulation, there are many other methods and functions available for handling strings.