How to use substring in a string?
In Python, you can find the position of a substring using the find() and index() methods of a string, and extract the substring using slice operations.
- search for a specific word or phrase within a larger text
- a small section of a larger string
s = "Hello, World!"
index = s.find("World")
print(index) # 输出: 7
- find the position of a specific string within another string
- locate
- a portion of a string
- Invalid value
s = "Hello, World!"
index = s.index("World")
print(index) # 输出: 7
- [from:start to finish]
- Commence
- finish
- begin
- The conclusion
s = "Hello, World!"
substring = s[7:12]
print(substring) # 输出: World
- The last element of the list.
- second to last character
s = "Hello, World!"
substring = s[-6:-1]
print(substring) # 输出: World
These techniques and procedures can assist you in locating and extracting substrings within a string.