Get the App
SLTechnology News&Howtos  ›  Development  › 

How does python intercept a specific part of a string

Shulou Source: shulou.com Published: 2022-05-31 17:50:48 11月02日 Update

This article mainly introduces "how python intercepts a specific part of a string". In daily operation, I believe many people have doubts about how python intercepts a specific part of a string. The editor consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubt of "how to intercept a specific part of a string by python". Next, please follow the editor to study!

The operating environment of this tutorial: windows7 system, Python 3.9.1 Dell G3 computer.

1. Intercept a string of a specific length. Use s [:] to intercept a segment of a character in a string, following the principle of closing left and opening right, starting with 0 and ending with Xmur1.

S = "abcdefgh" # 1, a range of characters take a character print (s [0:3]) # abcprint (s [1:3]) # bcprint ("-") print (s [2:3]) # cprint (s [3:3]) # None # 2, With default parameters default parameter print (s [3:]) # defghprint (s [: 3]) # abcprint (s [:]) # abcdefghprint ("-") # 3, with a step parameter step size print ("This is not as common") But perfectly ok. ") print (s [1: 7:2]) # bdf 2 is the step size That is, output 1, 1 "2, 1" 2 "2 (1" 2 "2" 7 out of range) print (s [1: 7:3]) # be 3 is the step size, that is, output 1, 1 "3 (1" 3 "3" 7 out of range)

2. The string is intercepted according to the specified character, and the lower mark position of the character is obtained first.

Python provides the index function to check whether the string contains substrings, usually as specific characters, specific characters.

Str1 = "Hello.python"; str2 = "."; print str1.index (str2); # result 5 print str1.index (str2, 2); # result 5 print str1.index (str2, 10); # result error reported and no substring found. Follow the screenshot example str1 = "Hello.python"; str2 = "."; print str1.index (str2); # result 5 print str1 [: str1.index (str2)] # get "." Previous characters (excluding dots) result Hello print str1 [str1.index (str2):]; # get "." As a result of the previous characters (including dots), python ends the study of "how python intercepts specific parts of a string". I hope you can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Character string result part study step size more range help output utility next subscript position function parameter screenshot tutorial article method Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB MySQL Shulou Tech Info Xiaomi Shulou Information