line1
line2
line3
>>> | | | Backslash itself | >>> print("")
| | ' | Single quote | >>> print(''')
' | | " | Double quote | >>> print(""")
" | | a | Bell (alert) | >>> print("a")
(The computer will make a sound after execution.) | | b | Backspace | >>> print("Hello b World!")
Hello World! | | 00 | Null | >>> print("00")
>>> | | n | Newline | >>> print("n")
>>> | | v | Vertical tab | >>> print("Hello v World!")
Hello
World!>>> | | t | Horizontal tab | >>> print("Hello t World!")
Hello World!>>> | | r | Carriage return. Moves the content after `r` to the beginning of the string, replacing characters one by one until all content after `r` is placed at the start. | >>> print("HellorWorld!")
World!>>> print('google taobaor123456')
123456 taobao | | f | Form feed | >>> print("Hello f World!")
Hello
World!>>> | | yyy | Octal number, where y represents a character from 0~7. For example: `12` represents a newline. | >>> print("1101451541541574012715716215414441")
Hello World! | | xyy | Hexadecimal number, starting with `x`, where y represents the character. For example: `x0a` represents a newline. | >>> print("x48x65x6cx6cx6fx20x57x6fx72x6cx64x21")
Hello World! | | other | Other characters are output in their literal format. | | Using `r` to create a percentage progress bar: ## Example ```python import time for i in range(101): # Add progress bar graphic and percentage bar = '[' + '=' * (i // 2) + ' ' * (50 - i // 2) + ']' print(f"r{bar} {i:3}%", end='', flush=True) time.sleep(0.05) print() In the following example, we use different escape characters to demonstrate the effects of single quotes, newline, tab, backspace, form feed, ASCII, binary, octal, and hexadecimal numbers: ## Example ```python print(''Hello, world!'') # Output: 'Hello, world!' print("Hello, world!n How are you?") # Output: Hello, world! # How are you? print("Hello, world!t How are you?") # Output: Hello, world! How are you? print("Hello,b world!") # Output: Hello world! print("Hello,f world!") # Output: # Hello, # world! print("The ASCII value of 'A' is:", ord('A')) # Output: The ASCII value of 'A' is: 65 print("x41 is the ASCII code for A") # Output: A is the ASCII code for A decimal_number = 42 binary_number = bin(decimal_number) # Decimal to binary print('Converted to binary:', binary_number) # Converted to binary: 0b101010 octal_number = oct(decimal_number) # Decimal to octal print('Converted to octal:', octal_number) # Converted to octal: 0o52 hexadecimal_number = hex(decimal_number) # Decimal to hexadecimal print('Converted to hexadecimal:', hexadecimal_number) # Converted to hexadecimal: 0x2a --- ## Python String Operators The following table shows examples where variable `a` has the string value "Hello" and variable `b` has the value "Python": | Operator | Description | Example | | --- | --- | --- | | + | String concatenation | a + b outputs: HelloPython | | * | Repeat string | a*2 outputs: HelloHello | | [] | Access character by index | a outputs **e** | | [ : ] | Slice a part of the string, following the **left-inclusive, right-exclusive** principle. `str[0:2]` does not include the 3rd character. | a[1:4] outputs **ell** | | in | Membership operator - Returns True if the given character is found in the string | **'H' in a** outputs True | | not in | Membership operator - Returns True if the given character is NOT found in the string | **'M' not in a** outputs True | | r/R | Raw string - A raw string treats all characters literally, with no escape processing. It is created by prefixing the string with `r` or `R`. | print( r'n' )
print( R'n' ) | | % | Format string | See the next section. | ## Example (Python 3.0+) ```python a = "Hello" b = "Python" print("a + b outputs: ", a + b) print("a * 2 outputs: ", a * 2) print("a outputs: ", a) print("a[1:4] outputs: ", a[1:4]) if ("H" in a): print("H is in variable a") else: print("H is not in variable a") if ("M" not in a): print("M is not in variable a") else: print("M is in variable a") print(r'n') print(R'n') The output of the above example is: a + b outputs: HelloPython a * 2 outputs: HelloHello a outputs: e a[1:4] outputs: ell H is in variable a M is not in variable a n n --- ## Python String Formatting Python supports formatted string output. Although this can involve complex expressions, the most basic usage is to insert a value into a string with the format specifier `%s`. In Python, string formatting uses the same syntax as the `sprintf` function in C. ## Example (Python 3.0+) ```python print("My name is %s and I am %d years old!" % ('Xiao Ming', 10)) The output of the above example is: My name is Xiao Ming and I am 10 years old! Python string formatting symbols: | Symbol | Description | | --- | --- | | %c | Format a character and its ASCII code | | %s | Format a string | | %d | Format an integer | | %u | Format an unsigned integer | | %o | Format an unsigned octal number | | %x | Format an unsigned hexadecimal number | | %X | Format an unsigned hexadecimal number (uppercase) | | %f | Format a floating-point number, with optional precision after the decimal point | | %e | Format a floating-point number in scientific notation | | %E | Same as %e, but uses uppercase E | | %g | Shorthand for %f and %e | | %G | Shorthand for %f and %E | | %p | Format a variable's address in hexadecimal | Formatting operator auxiliary directives: | Symbol | Function | | --- | --- | | * | Define width or decimal precision | | - | Left-align the output | | + | Show a plus sign (+) for positive numbers | | | Show a space before positive numbers | | # | Prefix octal numbers with '0' and hexadecimal numbers with '0x' or '0X' (depending on 'x' or 'X') | | 0 | Pad numbers with '0' instead of the default space | | % | '%%' outputs a literal '%' | | (var) | Map a variable (dictionary argument) | | m.n. | m is the minimum total width, n is the number of digits after the decimal point (if applicable) | Starting with Python 2.6, a new string formatting function [str.format()](#) was added, which enhances string formatting capabilities. --- ## Python Triple Quotes Python triple quotes allow a string to span multiple lines. The string can contain newline characters, tab characters, and other special characters. Here is an example: ## Example (Python 3.0+) ```python para_str = """This is a multi-line string example. Multi-line strings can use the TAB character ( t ). They can also use the newline character . """ print(para_str) The result of the above example is: This is a multi-line string example. Multi-line strings can use the TAB character ( ). They can also use the newline character . Triple quotes free programmers from the complexities of quotes and special strings, maintaining a small block of text in a WYSIWYG (What You See Is What You Get) format from start to finish. A typical use case is when you need a block of HTML or SQL, where string concatenation and special character escaping would be very tedious. ```python errHTML = '''
ERROR
%s''' cursor.execute(''' CREATE TABLE users ( login VARCHAR(8), uid INTEGER, prid INTEGER) ''') --- ## f-string f-strings were added in Python 3.6 and are called literal string formatting. They provide a new syntax for string formatting. Previously, we used the percent sign (%): ## Example ```python >>> name = '' >>> 'Hello %s' % name 'Hello ' **f-string** formatting starts with `f`, followed by the string. Expressions inside the string are enclosed in curly braces `{}`. The variable or expression is evaluated and its value is inserted. Here is an example: ## Example ```python >>> name = '' >>> f'Hello {name}' # Replace variable 'Hello ' >>> f'{1+2}' # Use expression '3' >>> w = {'name': '', 'url': 'www..com'} >>> f'{w}: {w}' ': www..com' This method is clearly simpler, as you don't need to decide whether to use `%s` or `%d`. In Python 3.8, you can use the `=` symbol to append the expression and its result: ## Example ```python >>> x = 1 >>> print(f'{x+1}') # Python 3.6 2 >>> x = 1 >>> print(f'{x+1=}') # Python 3.8 x+1=2 --- ## Unicode Strings In Python 2, regular strings were stored as 8-bit ASCII, while Unicode strings were stored as 16-bit Unicode strings, allowing for a larger character set. The syntax was to prefix the string with **u**. In Python 3, all strings are Unicode strings. --- ## Python Built-in String Methods Python has many built-in string methods. Here are some common ones: | No. | Method & Description | | --- | --- | | 1 | [capitalize()](#) Converts the first character of the string to uppercase. | | 2 | [center(width, fillchar)](#) Returns a centered string of the specified width, padded with `fillchar` (default is a space). | | 3 | [count(str, beg= 0,end=len(string))](#) Returns the number of occurrences of `str` in the string. If `beg` or `end` is specified, it returns the count within that range. | | 4 | [bytes.decode(encoding="utf-8", errors="strict")](#) Python 3 does not have a decode method for strings, but we can use the `decode()` method of a bytes object to decode it. This bytes object can be created by `str.encode()`. | | 5 | [encode(encoding='UTF-8',errors='strict')](#) Encodes the string using the specified encoding. By default, it raises a ValueError if an error occurs, unless `errors` is set to 'ignore' or 'replace'. | | 6 | [endswith(suffix, beg=0, end=len(string))](#) Checks if the string ends with the specified `suffix`. If `beg` or `end` is specified, it checks within that range. Returns True if it does, False otherwise. | | 7 | [expandtabs(tabsize=8)](#) Replaces tab characters in the string with spaces. The default number of spaces is 8. | | 8 | [find(str, beg=0, end=len(string))](#) Checks if `str` is found in the string. If `beg` and `end` are specified, it checks within that range. Returns the starting index if found, otherwise -1. | | 9 | [index(str, beg=0, end=len(string))](#) Similar to `find()`, but raises an exception if `str` is not found. | | 10 | [isalnum()](#) Returns True if all characters in the string are alphanumeric (letters or numbers) and there is at least one character. Otherwise, returns False. | | 11 | [isalpha()](#) Returns True if all characters in the string are alphabetic and there is at least one character. Otherwise, returns False. | | 12 | [isdigit()](#) Returns True if all characters in the string are digits. Otherwise, returns False. | | 13 | [islower()](#) Returns True if all cased characters in the string are lowercase and there is at least one cased character. Otherwise, returns False. | | 14 | [isnumeric()](#) Returns True if all characters in the string are numeric characters. Otherwise, returns False. | | 15 | [isspace()](#) Returns True if all characters in the string are whitespace. Otherwise, returns False. | | 16 | [istitle()](#) Returns True if the string is titlecased (see `title()`). Otherwise, returns False. | | 17 | [isupper()](#) Returns True if all cased characters in the string are uppercase and there is at least one cased character. Otherwise, returns False. | | 18 | [join(seq)](#) Merges (concatenates) the string representations of the elements in the sequence `seq` into a new string, using the string as a separator. | | 19 | [len(string)](#) Returns the length of the string. | | 20 | [ljust(width[, fillchar])](#) Returns a left-justified string of the specified width, padded with `fillchar` (default is a space). | | 21 | [lower()](#) Converts all uppercase characters in the string to lowercase. | | 22 | [lstrip()](#) Removes leading whitespace or specified characters. | | 23 | [maketrans()](#) Creates a translation table for character mapping. The simplest call takes two arguments: the first is a string of characters to be replaced, and the second is a string of replacement characters. | | 24 | [max(str)](#) Returns the largest alphabetic character in the string `str`. | | 25 | [min(str)](#) Returns the smallest alphabetic character in the string `str`. | | 26 | [replace(old, new [, max])](#) Replaces all occurrences of `old` with `new`. If `max` is specified, it replaces at most `max` occurrences. | | 27 | [rfind(str, beg=0,end=len(string))](#) Similar to `find()`, but searches from the right. | | 28 | [rindex( str, beg=0, end=len(string))](#) Similar to `index()`, but searches from the right. | | 29 | [rjust(width,[, fillchar])](#) Returns a right-justified string of the specified width, padded with `fillchar` (default is a space). | | 30 | [rstrip()](#) Removes trailing whitespace or specified characters. | | 31 | [split(str="", num=string.count(str))](#) Splits the string using `str` as the delimiter. If `num` is specified, it splits into at most `num+1` substrings. | | 32 | [splitlines()](#) Splits the string at line breaks ('r', 'rn', 'n') and returns a list of lines. If `keepends` is False, line breaks are not included. If True, they are kept. | | 33 | [startswith(substr, beg=0,end=len(string))](#) Checks if the string starts with the specified substring `substr`. Returns True if it does, False otherwise. If `beg` and `end` are specified, it checks within that range. | | 34 | [strip()](#) Performs both `lstrip()` and `rstrip()` on the string. | | 35 | [swapcase()](#) Swaps uppercase characters to lowercase and vice versa. | | 36 | [title()](#) Returns a titlecased string, where words start with uppercase and the rest are lowercase (see `istitle()`). | | 37 | [translate(table, deletechars="")](#) Translates the string using the given translation table (containing 256 characters). Characters to be deleted are placed in the `deletechars` parameter. | | 38 | [upper()](#) Converts all lowercase characters in the string to uppercase. | | 39 | [zfill (width)](#) Returns a string of the specified width, right-justified, padded with zeros. | | 40 | [isdecimal()](#) Returns True if all characters in the string are decimal characters. Otherwise, returns False. |
YouTip