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

Format() method for Python string formatting

編輯:Python

Catalog

Formatting of strings

  Common format characters

Example :

 format() Method

【 example 1】

【 example 2】

Formatting of strings

  Common format characters

Format characters

explain

%s

character string  ( use str() Display of )

%r

character string  ( use repr() Display of )

%c

Single character

%b

Binary integer

%d

Decimal integer

%i

Decimal integer

%o

Octal integer

%x

Hexadecimal integer

%e

Index  ( The base is written as e)

%E

Index  ( The base is written as E)

%f、%F、%F

Floating point numbers

%g

Index (e) Or floating point  ( According to display length )

%G

Index (E) Or floating point  ( According to display length )

%%

character "%""%"

Example :

>>> x = 1235
>>> so="%o" % x
>>> so
"2323"
>>> sh = "%x" % x
>>> sh
"4d3"
>>> se = "%e" % x
>>> se
"1.235000e+03"
>>> chr(ord("3")+1)
"4"
>>> "%s"%65
"65"
>>> "%s"%65333
"65333"
>>> "%d"%"555" # Trying to convert a string to an integer for output , Throw an exception
TypeError: %d format: a number is required, not str
>>> int('555') # have access to int() Function to convert a valid numeric string to an integer
555
>>> '%s'%[1, 2, 3]
'[1, 2, 3]'
>>> str((1,2,3)) # have access to str() Function to convert any type of data to a string
'(1, 2, 3)'
>>> str([1,2,3])
'[1, 2, 3]'

 format() Method

More flexible , Not only can you format with position , It also supports formatting with position independent parameter names , And support sequence unpacking format string

【 example 1】

print("The number {0:,} in hex is: {0:#x}, the number {1} in oct is {1:#o}".format(5555,55))

Output :

The number 5,555 in hex is:0x15b3, the number 55 in oct is 0o67 

analysis :

{0:} perhaps {0} representative format(a0,a1,a2) Medium a0,{0:# Format characters } to a0 format  

【 example 2】

print("my name is {name}, my age is {age}, and my QQ is {qq}".format(name = "Dong Fuguo",age = 37,qq = "306467355"))

  Output :

my name is Dong Fuguo, my age is 37, and my QQ is 306467355


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