Python has an output format error, how to solve it?

  As we all know, Python is a fast, simple and powerful programming language, but we often encounter various problems in the process of programming in Python language, one of which is the output format error, How to solve it? The following is the detailed content:

  1. Incorrect use of markers

  In string formatting, the use of tokens is very important. Common tokens include %s, %d, %f, etc. Among them, %s represents a string, %d represents an integer, and %f represents a floating point number.

  If we use the wrong token, an error will be generated. For example:

  name = 'Tom'

  age = 18

  score = 95.8

  print('%s is %d years old, and his score is %d.' % (name, age, score))

  Output result:

  TypeError: %d format: a number is required, not float

  This is because score uses the %d tag, but score is a floating-point number, and the %f tag should be used. Therefore, we should change the code to:

  name = 'Tom'

  age = 18

  score = 95.8

  print('%s is %d years old, and his score is %.1f.' % (name, age, score))

  Output result:

  Tom is 18 years old, and his score is 95.8.

  We can also use the string.format() function or the f-string method to avoid tag usage errors.

  2. The parameters do not match

  We can also use the string.format() function or the f-string method to avoid tag usage errors.

  name = 'Tom'

  print('%s is %d years old.' % (name))

  Output result:

  TypeError: not enough arguments for format string

  This is because we only passed one parameter, but there are two markers, the code should be changed to:

  name = 'Tom'

  age = 18

  print('%s is %d years old.' % (name, age))

  Output result:

  Tom is 18 years old.

  3. Grammatical errors

  Syntax errors are one of the common mistakes in Python. Especially in string formatting, due to the wrong use of symbols such as brackets and quotation marks, it is easy to cause grammatical errors. For example:

  print('My name is {}. I'm {} years old.' .format('Tom', 18))

  Output result:

  File "", line 1

  print('My name is {}. I'm {} years old.' .format('Tom', 18))

  ^

  SyntaxError: invalid syntax

  This is because two single quotes are used in the above string, resulting in a parsing error. The code should be changed to:

  print("My name is {}. I'm {} years old." .format('Tom', 18))

  Output result:

  My name is Tom. I'm 18 years old.

Guess you like

Origin blog.csdn.net/oldboyedu1/article/details/131417522