1. String Formatting Output
1.1 Core Methods and Key Features
1. Plus (+) Concatenation Method
- Principle: Directly connects string literals with variables using + to form a complete string.
- Core Syntax: “Fixed Text” + Variable1 + “Fixed Text” + Variable2
Example:
name = “Zhang San”
info = “I am ” + name + “, I am 18 years old”
- Key Limitation: Only supportsstring concatenation, concatenating non-string types like integers (int) or floats directly will result in an error; they must be converted to strings using str() first.
- Applicable Scenarios: Only suitable forvery simple concatenation with very few variables (e.g., 1-2 variables).
2. Placeholder (%) Method
- Principle: First, use % + letter to indicate a “placeholder” in the string, then use % after the string to specify the variables to fill in (multiple variables are wrapped in a tuple).
- Core Placeholder Meanings:
- %s: String placeholder (universal placeholder, can automatically convert non-string types to strings);
- %f: Float placeholder (defaults to 6 decimal places, precision control needs to be learned later);
- %d/%i: Integer placeholder (%d represents decimal integers, and %i has the same function).
- Core Syntax: “Fixed Text%s, Fixed Text%f” % (Variable1, Variable2)
Example:
name = “Zhang San”
weight = 65.2; info = “I am %s, my weight is %f kg” % (name, weight)
3. f-string (Formatted String Literal) Method
- Principle: Add f (or F) at the beginning of the string, directly place variables in {}, and Python will automatically parse the variables inside {} and embed them in the string.
- Core Syntax: f”Fixed Text{Variable1}, Fixed Text{Variable2}”
Example:
age = 18
info = f”I am {age} years old, my weight is {65.2} kg”
- Core Advantages:
- No need to worry about variable types, Python will automatically convert non-string types to strings;
- Simplified syntax, variables are directly embedded in text, making it highly readable;
- It isthe recommended method for Python 3.6+.
1.2 Comparison Table of Three Methods
| Comparison Dimension | Plus (+) Concatenation Method | Placeholder (%) Method | f-string Method |
|---|---|---|---|
| Core Syntax | “a” + var + “b” | “a%s b%f” % (var1, var2) | f”a{var1} b{var2}” |
| Data Type Requirements | All participants must be strings (non-strings must be manually converted to str()) | %s can automatically convert to string, %f/%d must match types | Automatically converts all types to strings without manual handling |
| Code Conciseness | Poor (long concatenation chain with many variables) | Medium (must maintain correspondence between placeholders and variables) | Excellent (variables are directly embedded, intuitive and concise) |
| Flexibility | Very low (only supports concatenation, no other functions) | Medium (can control precision later, compatible with older versions) | High (supports expression embedding, e.g., f”2+3={2+3}” ) |
| Official Recommendation | Not recommended | Recommended for compatible scenarios | Preferred recommendation (Python 3.6+) |
| Typical Issues | Non-string concatenation results in an error | Mismatch between the number of placeholders and variables results in an error | No obvious issues (note that f cannot be omitted) |
1.3 Key Considerations
- Type Conversion for Plus Concatenation: If you need to concatenate integers/floats, you must first convert them using str(), for example: age = 18; “Age: ” + str(age) (writing “Age: ” + age directly will result in an error).
- Placeholder Matching Rules: Thenumber of placeholders in the string must match the number of subsequent variables, otherwise a TypeError will be triggered (e.g., if there are 2 placeholders but only 1 variable is passed).
- f-string’s f cannot be omitted: Forgetting to add f at the beginning of the string will cause {} to be treated as ordinary characters, and the variables cannot be parsed (e.g., “My name is {name}” will output “My name is {name}” instead of the variable value).
- The Universality of %s is Limited: Although %s can be compatible with all types, if you need to control the precision of floating-point numbers (e.g., keeping 2 decimal places), you still need to use %f (to be explained in later chapters), %s cannot achieve precision control.
2. String Placeholder Precision Control
2.1 Core Control Logic
All commonly used placeholders (%s / %f / %d / %i) support the %M.N type format, which controls precision and width through M and N, with the following general rules:
- M (Minimum Width): Controls the minimum number of character positions for the output content
- If the content length < M: fill withspaces; if the content length > M: M becomes ineffective
- Positive M: right-aligned; negative M: left-aligned (applies to all placeholders)
- N (Precision): Controls the detail precision of the content, the meaning varies with the type of placeholder (core difference)
2.2 Comparison of Precision Control Rules for Each Placeholder
| Placeholder Type | Applicable Data | M (Minimum Width) Effect | N (Precision) Effect | Special Rules |
|---|---|---|---|---|
| %s | String | Controls the minimum display width of the string, fills with spaces if insufficient | Controlsthe maximum number of output characters: – N ≤ string length: truncate to the first N characters; – N > string length: N becomes ineffective (no padding) | No additional processing, only character truncation / space filling |
| %f | Float | Controlsoverall width: (integer part + decimal point + decimal part), fills with spaces if insufficient | Controlsthe number of decimal places: – Default N=6 (automatically displays 6 decimal places if not set); – N < original decimal places: round off; – N > original decimal places: fill with 0 | Only placeholder that supportsrounding. |
| %d / %i | Integer | Controls the minimum display width of the integer, fills with spaces if insufficient | Controlsthe minimum number of digits for the integer: – N ≤ integer digits: N becomes ineffective; – N > integer digits: fill with 0 (fill in front of the integer) | If receiving a float: directlytruncate the decimal part (no rounding) |
2.3 Key Pitfalls
- %d and Float Conflict: If using %d to receive a float (e.g., print(“Weight: %d” % 65.9), Python will directly truncate the decimal part (output 65), rather than rounding — this is a “forced conversion due to type mismatch”, unrelated to %f’s precision control.
- %s N Does Not Fill: When N is greater than the string length (e.g., print(“Name: %.3s” % “Zhang San”), it will not fill with spaces / 0, only output the complete string (Zhang San), which differs from the N filling rules of %f / %d.
2.4 Key Focus in Actual Development
Clarify:99% of scenarios only need to master %f N control, for example:
- %.1f: Keep 1 decimal place (rounding)
- %.2f: Keep 2 decimal places (commonly used for amounts, weights, etc.)
- No need to memorize all rules, mastering %f’s precision control will meet most needs.
3. String Escape Characters
3.1 Basic Definition of Escape Characters
Starts withbackslash (\) and is used to represent special characters that cannot be directly written in strings (e.g., single quotes, new lines, etc.). Python will treat “\ + subsequent characters” as a whole for parsing, rather than two separate characters, thus resolving “character conflicts” or “special format requirements”.
3.2 Comparison Table of Common Escape Characters
| Escape Character Type | Syntax | Core Function | Example Code | Output Result |
|---|---|---|---|---|
| Single Quote Escape | ‘ | In a string wrapped in single quotes, output a single quote normally (to avoid truncating the string) | print(‘Python allows using ‘single quote’ to wrap strings’) | Python allows using ‘ single quote ‘ to wrap strings |
| Double Quote Escape | “ | In a string wrapped in double quotes, output a double quote normally (to avoid truncating the string) | print(“Python allows using ‘double quote’ to wrap strings”) | Python allows using “double quote” to wrap strings |
| New Line | \n | Starts output froma new line | print(“Registration Info:\nName\nAge\nPhone Number”) | Registration Info: Name Age Phone Number |
| Backslash Escape | \ | Outputs a single backslash normally (to resolve conflicts in parsing paths, special symbols) | print(“D:\nice\file.txt”) | D:\nice\file.txt |
| Backspace | \b | Deletes itsprevious character (only retains the final result, no intermediate deletion animation) | print(“helloo\b”) | hello |
| Cursor Return to Start of Line | \r | Returns the cursor to the beginning of the current lineand overwrites the original content | print(“67%\r68%”) | 68% |
| Horizontal Tab | \t | Moves the cursor to the next “tab stop” (achieving grouped alignment) | print(“AB\tCD”) | AB CD # In PyCharm, tab = 4 characters |
3.3 Key Considerations
- Distinction Between Slash and Backslash: Escape characters must use “\” (backslash), and must not be confused with the ” / ” (slash) on the keyboard, otherwise they will not work.
- Tab Stop Environment Differences:
- In PyCharm, 1 tab stop = 4 character positions by default;
- In the terminal (CMD), 1 tab stop = 8 character positions by default;
- You can force the tab stop to be 4 characters using the string method .expandtabs(4) (to adapt to multi-environment alignment).
- Special Nature of Chinese Characters: 1 Chinese character occupies 2 English character positions, when using \t to align Chinese content, you need to adjust the number of tabs based on the number of Chinese characters to avoid misalignment.
- Practical Application Scenarios:
- \b: Used to achieve a “typewriter correction effect” (requires combining with loops, delay modules);
- \r: Used to achieve a “progress loading bar” (requires combining with loops, percentage calculations).
4. Data Type Conversion
4.1 Necessity of Data Type Conversion
The core reasons for performing data type conversion in Python programming include:
- User input data (obtained through the input() function) is by defaultstring type, and if mathematical operations are needed, it must be converted to numeric types (int/float).
- When writing to files, onlystring type is supported, and other types of data must be converted before writing.
- Content read from databases is by defaultstring type, and if mathematical operations are needed, it must be converted to numeric types.
- Different systems/interfaces may have inconsistent specifications, requiring data format adaptation through type conversion.
4.2 Detailed Explanation of Core Conversion Functions
Three core built-in functions for basic data type conversion in Python, with the syntax unified as “function name(data to be converted)”, returning the converted data, which can be received by a variable.
1. str(): Convert to String Type
- Syntax: str(data to be converted)
- Core Rule: Any data type can be converted to a string (including complex types like lists, dictionaries, etc. that will be learned later), with no failure scenarios for conversion.
- Example:
- Convert integer: str(18) → returns string “18”
- Convert float: str(75.6) → returns string “75.6”
- Variable reception: result = str(123) → result type is string
2. int(): Convert to Integer Type
- Syntax: int(data to be converted)
- Successful Conversion Scenarios:
- Float: directlydiscard the decimal part (no rounding), e.g., int(15.6) → 15, int(9.9) → 9.
- Pure numeric string: allows stringswith spaces on both sides (automatically removes spaces), e.g., int(“79″) → 79, int(” 45 “) → 45.
- Itself as an integer: e.g., int(48) → 48 (syntax is legal but has no practical meaning).
- Failure Scenarios (will raise an error):
- Strings with spaces in between numbers: e.g., int(“7 9”) (spaces between numbers).
- Non-numeric strings: e.g., int(“Hello”), int(“abc”).
- Strings mixing numbers and non-numbers: e.g., int(“79个”), int(“x123”).
- Strings with decimal points: e.g., int(“15.6”) (even if the content is numeric, it cannot be directly converted to int).
3. float(): Convert to Float Type
- Syntax: float(data to be converted)
- Successful Conversion Scenarios:
- Integer: automatically adds .0 after conversion, e.g., float(18) → 18.0.
- Pure numeric / string with decimal point: allows stringswith spaces on both sides (automatically removes), e.g., float(“48″) → 48.0, float(” 5.7 “) → 5.7.
- Itself as a float: e.g., float(14.8) → 14.8 (syntax is legal but has no practical meaning).
- Failure Scenarios (will raise an error):
- Strings with spaces in between numbers/decimal points: e.g., float(“5. 7”) (space after the decimal point), float(“1 23.4”).
- Non-numeric strings: e.g., float(“Hello”), float(“test”).
- Strings mixing numbers and non-numbers: e.g., float(“5.7元”), float(“3a.2”).
- Strings with multiple decimal points: e.g., float(“5.23.12”) (format is invalid).
4.3 Comparison Table of Core Conversion Functions
| Conversion Function | Target Conversion Type | Convertible Data Range | Special Rules | Conversion Tolerance |
|---|---|---|---|---|
| str() | String | All data types (int/float/list, etc.) | No special restrictions, directly converted to string format | Highest (100% success) |
| int() | Integer | 1. float (discard decimal) 2. pure numeric string (no spaces in between) 3. itself as int | 1. No rounding2. Automatically removes spaces on both sides of the string | Lower (only supports specific formats) |
| float() | Float | 1. int (adds .0) 2. pure numeric / string with decimal point (no spaces in between) | 1. Integer to float adds .02. Automatically removes spaces on both sides of the string | Medium (more tolerant than int, but does not support multiple decimal points/mixing) |
4.4 Key Considerations
- Function Return Values: str() / int() / float() will all return the converted value, which must be received by a variable (e.g., res = int(15.6)) to be used later; otherwise, the conversion result will be discarded.
- Visual Distinction Misunderstanding: The integer printed in the console (e.g., 18) and the string (e.g., “18”) have no visual difference, and the type of the converted result must be verified using the type() function (e.g., type(res)).
- Practical Priority: The success of type conversion depends on data format, and the rules must be mastered through extensive coding practice (rather than just watching) to avoid errors due to format issues in actual programming.
5. Arithmetic Operators
5.1 Comparison Table of Common Arithmetic Operators
| Operator Symbol | Name | Core Function | Python Example | Result | Key Considerations |
|---|---|---|---|---|---|
| + | Addition | Adds two numbers | 9 + 7 | 16 | No special symbol differences, consistent with mathematical logic |
| – | Subtraction | Subtracts two numbers | 7 – 2 | 5 | No special symbol differences, consistent with mathematical logic |
| * | Multiplication | Multiplies two numbers | 3 * 4 | 12 | Cannot use “X” instead, must use asterisk |
| / | Division | Divides two numbers | 9 / 6 | 1.5 | 1. Cannot use backslash “\” instead, must use slash;2. The result must be a float, even if it divides evenly (e.g., 9 / 3 = 3.0) |
| // | Floor Division | Takes the integer part after dividing two numbers | 9 // 6 | 1 | Ignores the decimal part, only retains the integer part of the quotient |
| % | Modulus (Remainder) | Takes the remainder after dividing two numbers | 9 % 6 | 3 | The result is “dividend – divisor × quotient” (e.g., 9 – 6×1 = 3) |
| ** | Exponentiation | Calculates “base raised to the power of exponent” | 2 ** 3 | 8 | Left side is the base, right side is the exponent (e.g., 3**2 means 3 squared) |
5.2 Core Considerations
- Symbol Misunderstanding: Must strictly distinguish between operator symbols and mathematical symbols, especially multiplication (* ≠ “X”), division (/ ≠ \), backslash is only used for escape characters, do not confuse.
- Data Type Characteristics: Division (/) results in a float regardless of whether it divides evenly; other operators (e.g., +, -, *) result type varies with operands (integer operands result in integers, including floats results in floats).
- Code Writing Norms: Python officially recommends adding 1 space on each side of the operator (e.g., 9 + 7 instead of 9+7) to improve code readability.
6. String Escape Characters
6.1 Comparison Table of Common Escape Characters
| Escape Character | Function Description | Example Code | Expected Output |
|---|---|---|---|
| ‘ | In a string wrapped in single quotes, output a single quote (to avoid truncating the string) | print(‘Python allows using ‘single quote’ to define strings’) | Python allows using ‘ single quote ‘ to define strings |
