When writing code, we often deal with strings. There are usually three forms of controlling string format in Python: STR%, str.format(), f-str. the usage is the same, but there are some differences.
Let's have a look~~~
1, % usage
1. String output
>>>print('hi! %s!'%('Echohye')) # If there is only one number, the% can be followed without parentheses, such as print ('Hi!% s! '%'echohye'), the same below hi! Echohye! >>> name = 'Echohye' >>> print('hi! %s'%(name) hi! Echohye >>> id = '123' >>> print('%s of id yes%s'%(name,id)) Echohye of id It's 123
2. Integer output
b. d, o and x are binary, decimal, octal and hexadecimal respectively.
>>> print('this year%d Years old'%(20)) I'm 20 years old
3. Floating point output
%f - retain six significant digits after the decimal point
%. 2f, 2 decimal places reserved
>>> print('%f'%1.2345) 1.234500 >>> print('%.2f'%1.2345) 1.23
%e - retain six significant digits after the decimal point and output in exponential form
%. 2e, keep 2 decimal places and use scientific counting method
>>> print('%e'%1.11111) 1.111110e+00 >>> print('%.2e'%1.11111) 1.11e+00
%g - on the premise of ensuring six significant digits, decimal method shall be used, otherwise scientific counting method shall be used
%. 2g, keep 2 significant digits, and use decimal or scientific counting method
>>> print('%g'%1.2345678) 1.23457 >>> print('%.2g'%1.2345678) 1.2
4. Placeholder width output
%20s-Right aligned, placeholder 10 bits %-20s-Left aligned, placeholder 10 bits %.3s-Intercept 3 characters %20.3s-20 Bit placeholder, intercepting 3 characters %-10s%10s-Left 10 digit placeholder, right 10 digit placeholder
Summary: if it is a positive number before the decimal point, it is aligned to the right; If there is a negative number before the decimal point, align it to the left; The number after the decimal point is the number of digits intercepted
Formatter
The format character reserves a position for the real value and controls the format of the display. Type control codes can be used to display the following types:
%s string (displayed in str())
%r string (display with repr())
%c single character
%b binary integer
%d decimal integer
%i decimal integer
%o octal integer
%x hexadecimal integer
%E index (base is written as e)
%E index (base is written as E)
%f floating point number
%F floating point number, same as above
%g index (e) or floating point number (according to the display length)
%G index (E) or floating point number (according to display length)
>>> print('%20s'%('hi! Echohye')) hi! Echohye >>> print('%-20s'%('hi! Echohye')) hi! Echohye >>> print('%.3s'%('hi! Echohye')) hi! >>> print('%20.3s'%('hi! Echohye')) hi! >>> print('%-10s%10s'%('hi! ','Echohye')) hi! Echohye Also note the following >>> print('%5d'%3) 3 >>> print('%05d'%3) 00003 >>> print('%05s'%'3') 3
2, str.format() usage
Introduction to official documents:
Python2. Starting from 6, a new function str.format() for formatting strings is added, which enhances the function of string formatting.
The basic syntax is to replace the previous% by {} and:.
The format function can accept unlimited parameters, and the positions can be out of order.
Let's study it together
1. String output
>>>"{} {}!".format("hello", "Echohye") # Do not set the specified location, in the default order 'hello Echohye!' >>> "{0} {1}!".format("hello", "Echohye") # Set specified location 'hello Echohye!' >>> "{1} {0}!".format("hello", "world") # Set specified location 'Echohye hello!'
Set parameters with:
# Setting parameters through dictionary site = {"name": "Echohye", "wxNum": "Echo_hyee"} print("name:{name}, wechat number:{wxNum}".format(**site)) #**Can't fall # Set parameters through list index list = ['Echohye', 'Echo_hyee'] print("name:{0[0]}, wxNum: {0[1]}".format(list)) #"0" cannot be dropped #What about down there >>> list = [['Echohye', 'Echo_hyee'],['waiter', '12345']] >>> print("name:{0[0]}, wxNum: {0[1]}".format(list)) name:['Echohye', 'Echo_hyee'], wxNum: ['waiter', '12345'] >>> print("name:{0[1][0]}, wxNum: {0[1][1]}".format(list)) Name: Waiter, wxNum: 12345 >>> print("name:{0[0]}, wxNum: {0[1]}".format(list[0])) name: Echohye, wxNum: Echo_hyee
I can only say flexible use
2. Integer output
>>> print('{}'.format(1314)) 1314 >>>print('{:.0f}'.format(1314.22) 1314 #I don't want to introduce too much here. Personally, I think the usage is similar to the string output above
3. Floating point output
# Keep two decimal places >>>print('{:.2f}'.format(3.1415926)) 3.14 # The sign retains two decimal places, + indicates that + is displayed before a positive number and + is displayed before a negative number- >>>print('{:+.2f}'.format(3.1415926)) +3.14 >>> print('{:+.2f}'.format(-3.1415926)) -3.14 # Without decimals >>>print('{:.0f}'.format(3.1415926)) # '0' cannot be saved 3
4. Placeholder width output
# Fill the space with x, fill the left, and the width is 10 >>>print('{:x>10s}'.format('happy')) xxxxxhappy # Fill the space with x, fill the right, and the width is 10 >>>print('{:x<10s}'.format('happy')) happyxxxxx # Fill the space with x, fill both sides, and the width is 10 >>> print('{:x^10s}'.format('happy')) xxhappyxxx # If the number of placeholders is odd, the right is more than the left # Note: x can only specify one character, not multiple characters, and can be any character. The default is space >>> print('{:>10s}'.format('happy')) happy >>> print('{:&>10s}'.format('happy')) &&&&&happy >>> print('{:`>10s}'.format('happy')) `````happy >>> print('{:.>10s}'.format('happy')) .....happy >>> print('{:/>10s}'.format('happy')) /////happy >>> print('{:a>10s}'.format('happy')) aaaaahappy >>> print('{:2>10s}'.format('happy')) 22222happy
5. Other formats
# Comma separated number format >>> print('{:,}'.format(999999999)) 999,999,999 # Percentage format >>> print('{:%}'.format(0.99999)) # The default is still six decimal places 99.999000% >>> print('{:.2%}'.format(0.99999)) 100.00% >>> print('{:.2%}'.format(0.9999)) 99.99% # Exponential notation >>> print('{:.0e}'.format(1000000)) 1e+06 >>> print('{:.2e}'.format(1000000)) 1.00e+06 >>> print('{:.2e}'.format(0.1000000)) 1.00e-01 >>> print('{:.2e}'.format(0.000001)) 1.00e-06
Note: refer to "rookie tutorial" here
3, f-str usage
The usage of f-str is actually similar to that of str.format(), but I like to use f-str because it is more concise, convenient and efficient.
1. String output
# String input >>> print(f"my name is {'Echohye'},nice to meet you!") # Note the nesting of '' and '' my name is Echohye,nice to meet you! # Parameter substitution >>> name = 'Echohye' >>> print(f'my name is {name},nice to meet you!') my name is Echohye,nice to meet you! # String interception >>> name = 'Echohye' >>> print(f"my name is {'Echohye':.3s},nice to meet you!") my name is Ech,nice to meet you! >>> print(f"my name is {name:.3s},nice to meet you!") my name is Ech,nice to meet you! # Do you think it's convenient and fast? haha, of course, this Python 2 is not supported~
2. Integer output
>>> print(f'{1314}') 1314 >>> num = 1314 >>> print(f'{num}') 1314
3. Floating point output
...
4. Placeholder width output
...
The usage is basically the same as that of str.format(). If you want to continue mining, please refer to the previous ha, I won't go into more details. At present, I think the difference between the two is to put the contents of () brackets in str.format () in front of f '{:}'. Of course, there may be different places, but I haven't met them yet. Let's explore together
4, Let's talk about the print() function
The print() method is used to print out and is the most common function in python.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The following is an introduction to the parameters of print()
>>> help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
The specific meanings of parameters are as follows:
value -- represents the output object. When outputting multiple objects, you need to separate them with (comma).
Optional keyword parameters:
File – the file object to write to.
sep – used to space multiple objects.
End – used to set what to end with. The default value is newline \ n, which can be replaced with other characters.
Flush – whether the output is cached is usually determined by file, but if the flush keyword parameter is True, the stream will be forced to refresh.
Examples:
value parameter
>>> print('Echo','hye') Echo hye >>> print('Echo''hye') Echohye >>> print(1300,'+',14,'=',1300+14) #This is good. It's OK to mess around, haha 1300 + 14 = 1314 # The second one is actually useful. For example, if you code a long line of code and the computer screen is not enough to display, we can interrupt it with print("" ""), but it is still connected. >>> print('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa''cccccccccccccccccccccc') aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacccccccccccccccccccccc # I actually want to press enter in the middle, but IDLE Shell can't directly enter ~ ~ ~ but we can still enter in the py file^_^ file parameter
(omitted...)
sep parameters
>>> print('Echo','hye',sep='?') Echo?hye # Try to remove the comma between strings >>> print('Echo''hye',sep='?') Echohye >>> print('Echo','hye',sep=' ~I split~ ') Echo ~I split~ hye >>> print('Echo','hye',sep='\n') Echo hye >>> print('Echo','hye',sep='\t') Echo hye >>> print('Echo','hye',sep='\n\t') Echo hye # Summary: the characters in sep = '' replace commas, and are not limited to one character. They can be a string or an escape character. Professional characters can also team up - > (Ω) Д Ω) shock~~~ # I'm ignorant o(╥﹏╥) o
end parameter
Guess: the previous sep parameter is a comma in the middle, the end parameter is a comma at the end, and the default is' \ n '. If other parameters are set, it is equivalent to replacing' \ n ', and the usage should be the same. Let's practice
>>> print('Echo','hye',end='\nhere') Echo hye here >>> print('Echo','hye',end='\there') Echo hye here >>> print('Echo','hye',end='\n\there') Echo hye here # Practice shows true knowledge. Indeed, the usage of the end parameter is basically the same as that of the sep parameter flush parameter # Execute in PyCharm import time print("Loading", end="") for i in range(10): print(".", end='', flush=True) time.sleep(0.5) print() print("Loading", end="") for i in range(10): print(".", end='', flush=False) time.sleep(0.5) #result Loading.......... Loading..........
I don't see any difference. It may not be useful here, but I haven't found &umum~
That's all for the use of the print() function. Interested friends can continue to learn more about it~