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.

  1. search for a specific word or phrase within a larger text
  2. a small section of a larger string
s = "Hello, World!"
index = s.find("World")
print(index)   # 输出: 7
  1. find the position of a specific string within another string
  2. locate
  3. a portion of a string
  4. Invalid value
s = "Hello, World!"
index = s.index("World")
print(index)   # 输出: 7
  1. [from:start to finish]
  2. Commence
  3. finish
  4. begin
  5. The conclusion
s = "Hello, World!"
substring = s[7:12]
print(substring)   # 输出: World
  1. The last element of the list.
  2. 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.

bannerAds