|
Python string operatorsThe value of instance variable a in the following table is the string "Hello", and the value of variable b is "Python": Operator | Description | Instance | ##+ | String concatenation | a + b Output result: HelloPython | * | Repeated output string | a*2 Output result: HelloHello | [] | Get the characters in the string by index | a[1] Output resulte | [ : ] | Intercept part of the string | a[1:4] Output resultell | in | Member Operator - Returns True if the string contains the given character | H in a Output result 1 | not in | Member Operator - Returns True if the string does not contain the given character | M not in a Output result 1 | r/R | Raw Strings - Raw Strings: All strings are used literally, without escaping special or unprintable characters.
Raw strings have almost the same syntax as ordinary strings, except that the first quotation mark of the string is preceded by the letter "r" (can be uppercase or lowercase). | print r'\n' prints \n and print R'\n' prints \n | ##% Format string | Please see the next section. | | Example
#!/usr/bin/python3
a = "Hello"
b = "Python"
print("a + b 输出结果:", a + b)
print("a * 2 输出结果:", a * 2)
print("a[1] 输出结果:", a[1])
print("a[1:4] 输出结果:", a[1:4])
if( "H" in a) :
print("H 在变量 a 中")
else :
print("H 不在变量 a 中")
if( "M" not in a) :
print("M 不在变量 a 中")
else :
print("M 在变量 a 中")
print (r'\n')
print (R'\n') The output result of the above example is: a + b 输出结果: HelloPython
a * 2 输出结果: HelloHello
a[1] 输出结果: e
a[1:4] 输出结果: ell
H 在变量 a 中
M 不在变量 a 中
\n
\n Python string formatting
Python supports formatted string output. Although this can lead to very complex expressions, the most basic usage is to insert a value into a string with the string formatting character %s. In Python, string formatting uses the same syntax as the sprintf function in C. The following examples: #!/usr/bin/python3
print ("我叫 %s 今年 %d 岁!" % ('小明', 10)) The output results of the above examples: 我叫 小明 今年 10 岁! Python string formatting symbols: <tbody |
Symbol | Description |
---|
%c | Format Characters and their ASCII codes | ## %s | Format string | %d | Format integer | ## %u | Format unsigned integer | %o## Format unsigned Octal number | | %x Formatted unsigned hexadecimal number | | %X Format unsigned hexadecimal number (uppercase) | | %f Format floating point numbers, you can specify the precision after the decimal point | | %e Use scientific notation to format floating point numbers | | ## %E Same function %e, format floating point number in scientific notation | | %g Abbreviation for %f and %e | | %G Abbreviations for %f and %E | ## %p | Use ten Address of hexadecimal format variable | Format operator auxiliary command: symbol | Function | * | Define width or decimal point precision | - | Used for left alignment | + | Display plus sign (+) in front of positive numbers | <sp> | Display a space before positive numbers | | #Display zero ('0') before octal numbers, and '0' before hexadecimal numbers 0x' or '0X' (depending on whether 'x' or 'X' is used) | 0 | The displayed number is filled with '0' instead of the default The spaces | % | '%%' outputs a single '%' | (var) | Mapping variable (dictionary parameter) | ##m.n.m is the minimum total width of the display, n is the number of digits after the decimal point (if available) | |
Python triple quotesPython triple quotes allow a string to span multiple lines, and the string can contain newlines, tabs, and other special characters. The example is as follows #!/usr/bin/python3
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""
print (para_str) The execution result of the above example is: 这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( )。
也可以使用换行符 [
]。 Three quotation marks free programmers from the quagmire of quotation marks and special strings. Maintaining the format of a small string from beginning to end is the so-called WYSIWYG (What You See Is What You Get) format. A typical use case is when you need a piece of HTML or SQL, then using string combination, special string escaping will be very cumbersome. errHTML = '''
<HTML><HEAD><TITLE>
Friends CGI Demo</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window.history.back()"></FORM>
</BODY></HTML>
'''
cursor.execute('''
CREATE TABLE users (
login VARCHAR(8),
uid INTEGER,
prid INTEGER)
''')
Unicode stringIn Python2, ordinary strings are stored as 8-bit ASCII codes, while Unicode strings are stored as 16-bit unicode strings, so Able to represent more character sets. The syntax used is to prefix the string with u. In Python3, all strings are Unicode strings.
Python’s string built-in functionsPython’s commonly used string built-in functions are as follows:
Serial number | Method and description |
---|
1 | capitalize() Change the first character of the string characters are converted to uppercase | 2 | center(width, fillchar) Returns a specified width width centered String, fillchar is the filling character, and the default is space. | 3 | count(str, beg= 0,end=len(string)) Returns the occurrence of str in string The number of times, if beg or end is specified, returns the number of occurrences of str in the specified range | 4 | decode(encoding='UTF-8',errors= 'strict') Use the specified encoding to decode the string. The default encoding is string encoding. | 5 | encode(encoding='UTF-8',errors='strict') The encoding format specified by encoding Encoded string, if an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace' | 6 | endswith(suffix , beg=0, end=len(string)) Check whether the string ends with obj. If beg or end is specified, check whether the specified range ends with obj. If so, return True, otherwise return False. | 7 | expandtabs(tabsize=8) Convert the tab symbols in the string string to spaces, tab symbols The default number of spaces is 8. | 8 | find(str, beg=0 end=len(string)) Detect whether str is included in the string , if beg and end specify a range, check whether it is included in the specified range, if so, return the starting index value, otherwise return -1 | 9 | index(str, beg=0, end=len(string)) Same as find() method, except that if str is not in the string, an exception will be reported. | 10 | isalnum() Returns if the string has at least one character and all characters are letters or numbers
Return True, otherwise return False | 11 | isalpha() Returns True if the string has at least one character and all characters are letters,
Otherwise it returns False | 12 | isdigit() If the string contains only digits, it returns True, otherwise it returns False.. | 13 | islower() If the string contains at least one case-sensitive character, and all of them (case-sensitive ) characters are all lowercase, it returns True, otherwise it returns False | 14 | isnumeric() If the string only contains Numeric characters, returns True, otherwise returns False | 15 | isspace() If the string contains only spaces, then Returns True, otherwise False. | 16 | istitle() If the string is titled (see title() ) returns True, otherwise returns False | ##17 | isupper()If the string contains at least one case-sensitive characters, and all these (case-sensitive) characters are uppercase, return True, otherwise return False
| ##18 | join(seq)Use the specified string as the delimiter to combine all elements (string representations) in seq into a new string
| 19 | len(string)Return the string length
| 20 | ljust(width[, fillchar])Returns a new string that is left-aligned to the original string and filled to length width using fillchar. Fillchar defaults to spaces.
| 21 | lower()Convert all uppercase characters in the string to lowercase.
| 22 | lstrip()Truncate the spaces on the left side of the string
| 23 | maketrans()Create a conversion table for character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string, indicating the characters that need to be converted, and the second parameter is also a string. Indicates the target of conversion.
| 24 | max(str)Returns the largest letter in the string str.
| 25 | min(str)Returns the smallest letter in the string str.
| 26 | replace(old, new [, max])Replace str1 in the string with str2, if If max is specified, the replacement will not exceed max times.
| 27 | rfind(str, beg=0,end=len(string))Similar to the find() function, But it starts searching from the right.
| 28 | rindex(str, beg=0, end=len(string)) Similar to index(), but starts from the right.
| 29 | rjust(width,[, fillchar])Return An original string is right-aligned and filled with fillchar (default spaces) to a new string of length width
| 30 | rstrip() Remove spaces at the end of string string.
| 31 | split(str="", num=string.count(str)) num=string.count(str))
Use str as the separator to intercept the string. If num has a specified value, only num substrings will be intercepted
| 32 | splitlines( num=string. count('\n')) Separated by rows, return a list containing each row as an element. If num is specified, only num rows will be sliced. | 33 | startswith( str, beg=0,end=len(string)) Check whether the string starts with obj, if so, return True, otherwise return False. If beg and end specify values, the specified range is checked. | 34 | strip([chars]) Execute lstrip() and rstrip() on strings | 35 | swapcase() Convert uppercase to lowercase in the string and convert lowercase to uppercase | 36 | title() Returns a "titled" string, that is, all words start with uppercase letters, and the remaining letters are lowercase (see istitle() ) | 37 | translate(table, deletechars="") The table given by str (contains 256 characters) Convert string characters,
The characters to be filtered out are placed in the deletechars parameter | 38 | upper() Convert the lowercase letters in the string to uppercase | 39 | zfill (width) Returns a string with a length of width. The original string is right-aligned and filled with 0 | 40 | isdecimal() Checks whether the string contains only decimal characters, if so it returns true, otherwise it returns false. |
|