Common methods of python string
- What is an object?
Everything in python is an object, and each object has its own properties and methods.
The characteristic of an object is its properties, and the function of an object is its methods (functions). Many functions are built in the string.
- capitalize function:
The function of the capitalize function is to capitalize the first letter of the string and lowercase the rest.
Usage: newString = string Capitalize(), no parameter in parentheses. Example:
>>> name = 'xiaobai' >>> newname = name.capitalize() >>> newname 'Xiaobai'
When using the capitalize function, you should pay attention to:
Valid only for the first letter Valid only for letters Invalid if the first letter is capitalized
- casefold and lower functions:
The function of casefold and lower functions is to lowercase all strings.
Usage: newString = string casefold(),newstring = string.lower(), no parameters in parentheses. Example:
>>> name = 'XIAOBAI' >>> newname = name.casefold() >>> newname 'xiaobai'
>>> name = 'XIAOBAI' >>> newname = name.lower() >>> newname 'xiaobai'
When using casefold and lower functions, you should pay attention to:
Valid only for letters in a string The string is invalid if all letters are lowercase casefold You can convert letters in more languages to lowercase, and lower Conversion of English letters to lowercase only
- upper function:
The function of the upper function is to capitalize all strings.
Usage: newString = string Upper(), no parameters in parentheses. Example:
>>> name = 'xiaobai' >>> newname = name.upper() >>> newname 'XIAOBAI'
When using the upper function, you should pay attention to:
Valid only for letters in a string The string is invalid if all letters are capitalized
- swapcase function:
The function of the swapcase function is to convert all letters in the string to case, from uppercase to lowercase and from lowercase to uppercase.
Usage: newString = string Swapcase(), no parameters in parentheses. Example:
>>> name = 'XiaoBai' >>> newname = name.swapcase() >>> newname 'xIAObAI'
When using the swapcase function, you should pay attention to:
Valid only for letters in a string
- zfill function:
The function of zfill is to define the length of the string. If it is not satisfied, the missing part is filled with 0 in front of the string.
Usage: newString = string Zfill (width), the parameter is the length of the string. Example:
>>> name = 'xiaobai' >>> newname = name.zfill(10) >>> newname '000xiaobai'
When using the zfill function, you should pay attention to:
Independent of the character of the string If the defined length is less than the current string length, it does not change
- count function:
The count function returns the number of elements in the current string.
Usage: inttype = string Count (item). The parameter is the element of the number of queries. Example:
>>> name = 'my name is xiaobai' >>> newname = name.count('i') >>> newname 3
When using the count function, you should pay attention to:
If the element of the query does not exist, 0 is returned
- Startswitch and endswitch functions:
The function of startswitch is to judge whether the beginning of the string is a member (element), and the function of endswitch is to judge whether the end of the string is a member (element).
Usage: boottype = string startswith(item, start, end),booltype = string. Endswitch (item, start, end). The parameter is the element that matches the query. Start and end are optional parameters. It means to check whether the string starts with the specified content within the specified range. Example:
>>> name = 'my name is xiaobai' >>> newname = name.startswith('my') >>> newname True >>> newname = name.endswith('my') >>> newname False
- find and index functions:
The function of find and index functions is to return the position (index) of the query member (element).
Usage: inttype = string find(item),inttype = string.index(item), the parameter is the element of the query location. Example:
>>> name = 'my name is xiaobai' >>> name.find('n') 3 >>> name.index('x') 11
When using the find and index functions, you should pay attention to:
The position (index) in the string starts from 0 from left to right If find If the element is not found, it will be returned -1;If index If the element cannot be found, an error will be reported
- strip function:
The function of the strip function is to remove the specified elements on the left and right sides of the string. The default is a space.
Usage: newString = string Strip (item). The parameter is the element to be removed. Example:
>>> name = ' my name is xiaobai ' >>> newname = name.strip() >>> newname 'my name is xiaobai'
>>> name = 'my name is xiaobai' >>> newname = name.strip('my') >>> newname ' name is xiaobai' >>> newname = name.strip('name') >>> newname 'y name is xiaobai'
When using the strip function, you should pay attention to:
The passed in element is invalid if it is not at the beginning or end lstrip Only the specified elements at the beginning of the string are removed, and the default is space rstrip Only the specified element at the end of the string is removed, and the default is space
- replace function:
The function of replace is to replace the elements in the string with the specified elements, and can specify the number of replacement.
Usage: newString = string Replace (old, new, max). The parameter old represents the replaced element, new represents the newly specified element, and Max is optional. It represents the number of replaced elements. All elements are replaced by default. Example:
>>> name = 'my name is xiaobai' >>> newname = name.replace('xiaobai', 'xiaohei') >>> newname 'my name is xiaohei'
- isspace function:
The function of isspace is to judge whether the string is a string composed of only spaces and return True or false.
Usage: boottype = string Isspace(), no parameters in parentheses. Example:
>>> ' xiaobai'.isspace() False >>> ' '.isspace() True >>> 'my name is xiaobai'.isspace() False
Note: the string composed of spaces is not an empty string, that is' '! =' '.
- istitle function:
The istitle function is used to judge whether the string is a string of Title type (word initial capitalization) and return True or false.
Usage: boottype = string Istitle(), no parameter in parentheses. Example:
>>> 'My name is xiaobai'.istitle() False >>> 'My Name Is Xiaobai'.istitle() True >>> 'MY NAME IS XIAOBAI'.istitle() False
When using the istitle function, you should pay attention to:
This function applies only to English words
- isupper function:
The function of isupper is to judge whether a string is only composed of uppercase letters and return True or false.
Usage: boottype = string Isupper(), no parameter in parentheses. Example:
>>> 'xiaobai'.isupper() False >>> 'XIAOBAI'.isupper() True >>> 'MY NAME IS XIAOBAI'.isupper() True
When using the isupper function, you should pay attention to:
This function only checks the letters in the string and does not judge other characters
- islower function:
The islower function is used to judge whether a string is only composed of lowercase letters and return True or false.
Usage: boottype = string Islower(), no parameter in parentheses. Example:
>>> 'xiaobai'.islower() True >>> 'XIAOBAI'.islower() False >>> 'MY NAME IS XIAOBAI'.islower() False
When using the islower function, you should pay attention to:
This function only checks the letters in the string and does not judge other characters
- Character encoding format:
Coding is to encode words, numbers or other objects into numbers by predetermined methods, or convert information and data into specified electrical pulse signals. In order to ensure the correctness of coding, coding should be standardized, that is, there should be a standard coding format. Common coding formats include ASCII, ANSI, GBK, GB2312, UTF-8, GB18030 and UNICODE.
UTF-8 is an international common coding format, which can be successfully encoded and decoded in both Chinese and English.
Formatting of strings
- What is formatting?
In a fixed string, some elements change according to the value of the variable, which is called string formatting.
For highly repetitive information, the amount of code writing can be reduced by formatting.
- Formatting defined by type:
Formatting is implemented using the% operator; String is represented by% s and integer is represented by% d. Example:
>>> print('my name is %s, my age is %d' % ('xiaobai', 18)) my name is xiaobai, my age is 18
>>> list_1 = ['python', 'django', 'flask'] >>> print('my name is %s, my age is %s my book is %s' % ('xiaobai', 18, list_1)) my name is xiaobai, my age is 18 my book is ['python', 'django', 'flask']
>>> dict_1 = {'a': 1, 'b': 2, 'c': 3} >>> print('the dict is %s' % (dict_1)) the dict is {'a': 1, 'b': 2, 'c': 3}
A% is used to connect the format string and the format variable, and there is a space on both sides of% respectively.
- String formatting function - format:
The format function is used to format a string. The string body using format uses {} instead of the format character.
Usage: newString = string Format (* item), the parameter is a variable parameter. Example:
>>> name = 'my name is {}, my age is {}, my book is {}' >>> newname = name.format('xiaobai', 18, dict_1) >>> print(newname) my name is xiaobai, my age is 18, my book is {'a': 1, 'b': 2, 'c': 3}
>>> name = 'my name is {0}, my age is {1}, my book is {2}' >>> newname = name.format('xiaobai', 18, dict_1) >>> print(newname) my name is xiaobai, my age is 18, my book is {'a': 1, 'b': 2, 'c': 3}
- python3.6. New formatting method added:
Define a variable, add f in front of the string, and use {variable name} where formatting is required in the string.
Usage: newstring = f'string ', variables need to be defined in advance. Example:
>>> name = 'xiaobai' >>> age = 18 >>> print(f'my name is {name}, my age is {age}') my name is xiaobai, my age is 18
- Format symbol:
Formatting symbols are used to format various data types. Common are as follows:
Symbol | explain |
---|---|
%s | Format string, generic type |
%d | Format integer |
%f | Format floating point |
%u | Format unsigned integer (positive integer) |
%c | Formatting characters, that is, strings of length 1 |
%o | Format unsigned octal number |
%x | Format unsigned hexadecimal number |
%e | Scientific counting format floating point number |
- Escape character of string:
The function of converting specific characters into other meanings. Such characters are called escape characters. Common are as follows:
Symbol | explain |
---|---|
\n | Newline character, usually used at the end |
\t | Horizontal tab, i.e. tab |
\v | Vertical tab |
\a | Ring the bell |
\b | Backspace, move cursor, overwrite (delete previous) |
\r | enter |
\f | Turn pages |
' | Single quotation mark in escape string |
" | Double quotes in escape string |
\\ | Escape \, let \ not escape other characters |
In python, add r before the string to invalidate the escape character of the current string, or use \ \ to invalidate the escape character. Example:
>>> print(r'hello, xiaobai \f') hello, xiaobai \f >>> print('hello, xiaobai \\f') hello, xiaobai \f >>> print(r'hello, xiaobai \\') hello, xiaobai \\