程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python string formatting

編輯:Python

python String formatting

Mode one

and C The language is the same , Followed by several variables or values , Only one time bracket can be omitted

>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 10000)
'Hi, runner, you have $10000.'

Place holder

replace content

%3d %-3d %03d %+3d

Integers ( You can specify a complement 0 Or space (‘-’ Means to fill in a space on the right ), Or make up one +)

%2.2f %-2.2f …

Floating point numbers ( ditto , And the number of decimal places can be specified )

%s

character string ( It works forever , It converts any data type to a string )

%x

Hexadecimal integer

>>> print('%4d-%03d' % (3, 1))
3-001
>>> print('%-4d-%03d' % (3, 1))
3 -001
>>> print('%+4d-%03d' % (3, 1))
+3-001
>>> print('%10.2f' % 3.1415926)
3.14
>>> print('%d%%' % 3)
3%

use %% To represent a % character

Mode two :format()

>>> 'Hello, {0}, The results have improved {1:.1f}%'.format(' Xiao Ming ', 22.125)
'Hello, Xiao Ming , The results have improved 22.1%'

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved