We need to learn a lot about using Python strings. In fact, no matter what the environment is, you need to master the relevant string application. Next, let's take a look at how Python strings are written.
- # Coding: UTF-8
- # String operations
- # Use brackets [] to extract any consecutive characters from a string
- # Note: The expression in brackets is a string index, which indicates the position of a character in the string,
- # The index of the first character of the string in the brackets is 0, not 1
- # Len returns the length of the string
- Test_string = "1234567890"
- Print test_string [0] # result = 1
- Print test_string [1] # result = 2
- Print test_string [9] # result = 0
- Print len (test_string) # result = 10
- # Use for loop to traverse strings
- For I in test_string:
- Print I
- If (I = '5 '):
- Print "Aha, I find it! "
- Print type (I) # <type 'str'> 20
- # Extract part of a string
- # The operator [n: m] returns part of the string. Starts from the nth string and ends with the nth string.
- # Contains n, but not m.
- # If n is ignored, the returned string starts from index 0.
- # If m is ignored, the string starts from n and ends with the last string.
- Test_string = 'abcdefghijklmnopqrstuvwxy'
- Print test_string [0: 5] # result = 'abcde'
- Print test_string [8: 11] # result = 'ijk'
- Print test_string [: 6] # result = 'abcdef'
- Print test_string [20:] # result = 'uvwxyz'
- Print test_string [:] # result = 'abcdefghijklmnopqrstuvwxy'
The above is an introduction to the code used by Python strings.