当前位置:网站首页>Usage Summary of str.format() function [not 'str****{}'.Format()]
Usage Summary of str.format() function [not 'str****{}'.Format()]
2022-06-25 20:15:00 【dssgresadfsrgre】
Catalog
One 、 The cause of the article
3、 ... and 、 Main stream print expression
3.3 print(***{}***.format(*args)
Four 、format stand on one 's own 、 Get rid of print,“ Realize output freedom ”
One 、 The cause of the article
Because I am using 《 Deep learning - Case based understanding of deep neural networks 》 When studying , The code given by the author is similar to the following
# Input
cost = 6.512345
print(str.format(' The result value of the cost function ={0:.6f}', cost))
# Output
The result value of the cost function =6.512345Then I search on Baidu Google 「str.format」 Usage of , All you get is to put the body of the string in format Usage outside
print('{} {}'.format('hello','world')) # Without fields
hello world
print('{0} {1}'.format('hello','world')) # Numbered number
hello world
print('{0} {1} {0}'.format('hello','world')) # Out of order
hello world hello
print('{1} {1} {0}'.format('hello','world'))
world world helloSo I have to study it again and again , Then it is summarized as follows .
Two 、str.format(self,*args)
Private opinion ,str.format(self,*args) yes format A high-level expression of a function . It seems that if you use this method , Only one can be used to replace , Multiple substitutions will say that the parameter field is exceeded .
print('hello,world,I am {} {} {}'.format(' Small ',' bad ',' egg ') # Actual string substitution str
print(str.format('hello,world,I am {}',[' Little villain '])) # utilize str Under class format Function output string
print(str.format('hello,world,my number is {:.6f}', 8.888))
# Output results
hello,world,I am Small bad egg
hello,world,I am Little villain
hello,world,my number is 8.888000
# Wrong expression
print(str.format('hello,world,I am {} {} {}',[' Small ',' bad ',' egg ']) # It seems that only one parameter can be inserted into str in
#IndexError: Replacement index 1 out of range for positional args tuple3、 ... and 、 Main stream print expression
3.1 print('**%f**' %x)
print('This is a number equal to %f' %1.11)
# This is a number equal to 1.110000
What if you want to output multiple variables ? In parentheses !
print('This is a number equal to %f, instead of %d' %(1.11,1))
#This is a number equal to 1.110000, instead of 13.2 print(f'**{xx}**')
That is to say 「 Abbreviation f Put it in print front 」. As shown in the following code block .
Be careful : such f Method , Only one single quotation mark or double quotation mark can be followed , Can't be in f When you add double quotation marks, you also {} Put double quotation marks inside , Nor in f When you add a single quotation mark, you will also {} Put single quotation marks in it .
# Output number ( Integers 、 floating-point 、 The plural ), Direct output , No quotes
print(f'Hello world, I am No.{1}') # Direct output Hello world, I am No.1
one = 1
print(f'Hello world, I am No.{one}') # Indirect output Hello world, I am No.1
# Direct output string , If f Single quotation mark after , Be sure to use double quotation marks in curly braces
print(f'Hello world, I am {" Little villain "}.') # Hello world, I am Little villain .
print(f'Hello world, I am {' Little villain '}.') # SyntaxError: invalid syntax
# Or in f Double quotation mark after , You can put single quotation marks in the replacement part of the string
print(f"Hello world, I am {' Little villain '}.") # Hello world, I am Little villain .
# Use variables to output strings indirectly , You don't need quotation marks
y = ' Little villain '
print(f'Hello world, I am {y}.') # Hello world, I am Little villain .
3.3 print(***{}***.format(*args)
(1) If the curly braces contain nothing , Is to replace by position
(2) If it is replaced by serial number , You can rearrange the order . And if the element is a sequence ( list 、 Tuples 、 Dictionary, etc ), Or the plural , You can also replace its sub content ( The sub content of a complex number includes its real part and imaginary part , The sub contents of a list are the elements of its dimensions , The child content of a class is its variables or functions ).
print(' The real part of a complex number ={0.real}, Imaginary part ={0.imag}'.format(1+2j))
# The real part of a complex number =1.0, Imaginary part =2.0
print(' A sub content of the list is {0[1][1]}'.format([[1,2],[1,2]]))
# A sub content of the list is 2(3) Empathy , Replace by keyword , It can also be placed out of order .
(4) In an output body , Can include both 「 Replace by position 」 and 「 Replace by serial number 」.
print('{} {}'.format('hello','world')) # Without fields
hello world
print('{0} {1}'.format('hello','world')) # Numbered number
hello world
print('{0} {1} {0}'.format('hello','world')) # Out of order
hello world hello
print('{1} {1} {0}'.format('hello','world'))
world world hello
print('{a} {tom} {a}'.format(tom='hello',a='world')) # With the keyword
world hello worldFour 、format stand on one 's own 、 Get rid of print,“ Realize output freedom ”
It seems that most of the output with strings , You have to use print function , But the following expression , But you can avoid print monopoly , Achieve independent output freedom .
Empathy : Nor in f Back 、{} Use double or single quotation marks inside .
But this method has some defects , That is, the output string has single quotation marks .
The road to independence is hard 、 Questionable , however , We must believe —— Just stick to it , We will certainly catch up with the international advanced level ! Pay tribute to !!!
# The path of independence 1:a.format(b)
"{0} {1}".format("hello","world")
#'hello world'
# The path of independence 2:f"xxxx" or f'xxxx'
f"{'hello'} {'world'}"
or
f'{"hello"} {"world"}'
# The output is 'hello world'5、 ... and 、 Reference source
python print(% Usage and format usage )_wjqhit The column -CSDN Blog _print
python Of print(f‘)_wuli_xin The blog of -CSDN Blog _python in print(f)
边栏推荐
- [harmonyos] [arkui] how can Hongmeng ETS call pa
- PAT B1051
- Swin UNET reading notes
- Robotium_ (clickbyid method)
- Arduino read temperature
- Share a billing system (website) I have developed
- Bindgetuserinfo will not pop up
- String since I can perform performance tuning, I can call an expert directly
- Redis core article: the secret that can only be broken quickly
- 2.3 partial sum of square and reciprocal sequences
猜你喜欢

Remember to deploy selenium crawler on the server

Nnformer reading notes

Pcl+vs2019+opencv environment configuration

Applet password input box

JS asynchronism (I. asynchronous concept, basic use of web worker)

Understanding C language structure pointer

One picture to achieve the selected effect

JS canvas drawing an arrow with two hearts

Wechat applet cloud function does not have dependency option installed

5 minutes to learn how to install MySQL
随机推荐
<C>. Rolling phase division
Some pictures of real machine preview development and debugging are not shown
Web container basic configuration
Is it safe to open a new bond account
Applet multi image to Base64 upload
SQL statement select summary
Life cycle function of composite API
Please do not call Page constructor in files
Native JS array some method de duplication
4.ypthon function foundation
Jsonp function encapsulation
A necessary programming assistant for programmers! Smartcoder helps you easily integrate HMS core
Arduino : No such file or directory
通过启牛学堂开的股票账户可以用吗?资金安全吗?
5 minutes to learn how to install MySQL
Applet wx Request encapsulation
Applet request interface encapsulation
JS get the parameters in the URL link
在打新債開戶證券安全嗎?低傭金靠譜嗎
Expand and check the specified node when loading ztree