python string operation

  • 2021-12-12 05:16:43
  • OfStack

Directory 1. String method 1. String segmentation 2. String search, replacement 3. String judgment 2. Slicing operation (list, tuple can also) 1. Index 2. Slicing has 3 parameters [start: end: step]

1. String method

1. String segmentation

s.split() Split by space by default

s.split(',') Split by comma (1 list is returned, and the original string is not changed)


>>> s= " Now is the best , Don't say there is a long way to go , Time is hard to stay , Only 1 Go and never return "
>>> print(s.split(","))
[' Now is the best ', ' Don't say there is a long way to go ', ' Time is hard to stay ', ' Only 1 Go and never return ']
>>>

2. Find and replace strings

s.index(‘a') Find the character a and return the subscript, and return the first one when there are multiple characters; Nonexistent characters report errors
s.rindex(‘a') Find the last 1 character a and return subscript. Error is reported for nonexistent characters

s.find(‘a') Find the character a and return the subscript, and return the first one when there are multiple characters; Returns-1 for nonexistent characters
s.rfind(‘a') Find the last 1 character a and return the subscript, and return the first one when there are multiple characters; Returns-1 for nonexistent characters


>>> s = "123456654321"
>>> s.index("2")

>>> s.rindex("2")

>>> s.index("10")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.find("10")
-1
>>>

max, min: Find the minimum and maximum value (ASCII code)


>>> s = "123456654321"
>>> max(s)
'6'
>>> min(s)
'1'
>>>

s.capitalize() Capital initials

s.count(‘x') Find the number of times a character appears in a string

s.center(n,'*') Put the string in the middle, complete both sides with *, and n is a number, indicating that the distance from the beginning to the end of the string is n


>>> s = "today is a good day"
>>> s.capitalize()
'Today is a good day'

>>> s.count("o")


>>> s.center(50,"*")
'***************today is a good day****************'
>>>

s.replace(oldstr, newstr) String substitution


>>> s = " It's sunny today "
>>> s.replace(" Sunny day "," Rainy days ")
' It's rainy '
>>>

s.split(',')0 String formatting

s.format_map(d) String formatting, passing in a dictionary

s.lower() Convert a string to uppercase

s.lower() Convert a string to lowercase

s.strip() Clear the space on the side of string 2

s.join() Splice string, which can be a list, dictionary, etc.

s.startswith(n) Determines whether the string begins with the string n and returns the value of bool
s.endswitch(n) Determines whether the string ends with the string n and returns the bool value


>>> s = "123456"
>>> s.startswith("1")
True
>>> s.startswith("2")
False
>>>

s.encode(“utf-8”) Use utf-8 Encode a string

Note: 1 encoding method should be used for encoding and decoding

s.decode(“utf-8”) Use utf-8 Decoding a string

3. String judgment

(All returned bool types True, False):

s.isalunm() Determining whether the string s is composed of upper and lower case letters and numbers
s.isalpha() It is determined whether the string s is composed of letters
s.isasscii() It is judged whether the string s is a symbol in the ASCII code
s.isdecima() Determining whether the string s is a number
s.isdigit() Determining whether the string s is a number
s.isidentifier() Judge valid symbol
s.islower() Determine whether the string s is all lowercase
s.isupper() Determine whether the string s is all uppercase
s.rindex(‘a')0
s.rindex(‘a')1 Determine whether the string s has spaces
s.rindex(‘a')2 Determine whether the string s is a title (capitalize the first letter of every 1 word)

2. Slice operation (list and tuple can also be used)

1. Index

A string is composed of multiple characters, and there is an order between the characters. This order number is called an index ( index ). Python Allows single or multiple characters in a string to be manipulated by index, such as getting the character at the specified index, returning the index value of the specified character, and so on.

Gets a single character (string subscript starts from 0)

s represents the string name, and index (string subscript) represents the index value.
s[index]
s [index:] represents the truncation from the subscript index to the end


>>> s = "python Index of string "
>>> s[5]
'n'

>>> s[5:]
'n Index of string '

>>> s[8]
' String '

>>> s[-1]
' Cite '

>>> s[::-1]
' String character of lead cable nohtyp'

Python has positive and negative indexes:

Positive index: When starting with the left end of the string (the beginning of the string), the index is counted from 0; The index of the first character of the string is 0, the index of the second character is 1, and the index of the third string is 2... Negative index: When starting at the right end of the string (the end of the string), the index is counted from-1; The index of the penultimate character of the string is-1, the index of the penultimate character is-2, and the index of the penultimate character is-3 …, so the string inversion is very convenient

>>> s = "python Index of string "
>>> s[::-1]
' String character of lead cable nohtyp'

2. Slice has 3 parameters [start: end: step]

The first parameter start Where to start slicing The second parameter end Where does the cut end The third parameter step Step size means that every step size is taken once

s = "python Index of string "
>>> s[1:5]
'ytho'
>>> s[1::3]
'yo Fourier cord '
>>> s[len(s):0:-1]
' String character of lead cable nohty'   # Slice forward from the end and decrease in turn. Realize inversion 


Related articles: