Python有几种字符串格式化?

问答Python有几种字符串格式化?
1
水中的鱼 asked 3年 ago

Python种有几种字符串格式化?

17 Answers
0
帅哥 你好. answered 3年 ago

Python字符串格式化主要有两种方式:分别为占位符(%)和format方式 。文末还有2种要介绍,所以总共有4种 。
其中,占位符(%)方式比较老,而format方式是比较先进的,目前两者共存。占位符方式在Python2.x中用的比较广泛,随着Python3.x的使用越来越广,format方式使用的更加广泛。
下面分别来说说这几种的区别:
1、百分号方式

%[(name)][flags][width].[precision]typecode

  • (name)      可选,用于选择指定的key
  • flags          可选,可供选择的值有:
    • +       右对齐;正数前加正好,负数前加负号;
    • –        左对齐;正数前无符号,负数前加负号;
    • 空格    右对齐;正数前加空格,负数前加负号;
    • 0        右对齐;正数前无符号,负数前加负号;用0填充空白处
  • width         可选,占有宽度
  • .precision   可选,小数点后保留的位数
  • typecode    必选
    • s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置
    • r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
    • c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置
    • o,将整数转换成 八  进制表示,并将其格式化到指定位置
    • x,将整数转换成十六进制表示,并将其格式化到指定位置
    • d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
    • e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
    • E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
    • f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
    • F,同上
    • g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
    • G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
    • %,当字符串中存在格式化标志时,需要用 %%表示一个百分号

注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式
常用格式化:

tpl = "i am %s" % "alex"

tpl = "i am %s age %d" % ("alex"18)

tpl = "i am %(name)s age %(age)d" % {"name""alex""age"18}

tpl = "percent %.2f" % 99.97623

tpl = "i am %(pp).2f" % {"pp"123.425556, }

tpl = "i am %.2f %%" % {"pp"123.425556, }

2、Format方式

[[fill]align][sign][#][0][width][,][.precision][type]

  • fill           【可选】空白处填充的字符
  • align        【可选】对齐方式(需配合width使用)
    • <,内容左对齐
    • >,内容右对齐(默认)
    • =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
    • ^,内容居中
  • sign         【可选】有无符号数字
    • +,正号加正,负号加负;
    •  -,正号不变,负号加负;
    • 空格 ,正号空格,负号加负;
  • #            【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
  • ,            【可选】为数字添加分隔符,如:1,000,000
  • width       【可选】格式化位所占宽度
  • .precision 【可选】小数位保留精度
  • type         【可选】格式化类型
    • 传入” 字符串类型 “的参数
      • s,格式化字符串类型数据
      • 空白,未指定类型,则默认是None,同s
    • 传入“ 整数类型 ”的参数
      • b,将10进制整数自动转换成2进制表示然后格式化
      • c,将10进制整数自动转换为其对应的unicode字符
      • d,十进制整数
      • o,将10进制整数自动转换成8进制表示然后格式化;
      • x,将10进制整数自动转换成16进制表示然后格式化(小写x)
      • X,将10进制整数自动转换成16进制表示然后格式化(大写X)
    • 传入“ 浮点型或小数类型 ”的参数
      • e, 转换为科学计数法(小写e)表示,然后格式化;
      • E, 转换为科学计数法(大写E)表示,然后格式化;
      • f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
      • F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
      • g, 自动在e和f中切换
      • G, 自动在E和F中切换
      • %,显示百分比(默认显示小数点后6位)

常用格式化:

tpl = "i am {}, age {}, {}".format("seven"18'alex')
 
tpl = "i am {}, age {}, {}".format(*["seven"18'alex'])
 
tpl = "i am {0}, age {1}, really {0}".format("seven"18)
 
tpl = "i am {0}, age {1}, really {0}".format(*["seven"18])
 
tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
 
tpl = "i am {name}, age {age}, really {name}".format(**{"name""seven""age"18})
 
tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([123], [112233])
 
tpl = "i am {:s}, age {:d}, money {:f}".format("seven"1888888.1)
 
tpl = "i am {:s}, age {:d}".format(*["seven"18])
 
tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
 
tpl = "i am {name:s}, age {age:d}".format(**{"name""seven""age"18})

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(151515151515.876232)

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(151515151515.876232)

tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)

tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

那到底要怎么选择呢?Python字符串格式化经验法则:如果你的格式化字符串是由用户提供的,那么就是用模板字符串避免安全问题。不然如果是Python 3.6+的话,就使用字符串插值/f-Strings,如果不是就使用str.format进行字符串格式化。

0
Ultimate answered 2月 ago

Hi, would you like more business leads at a lower cost? Currently http://GetMoreBusinessLeadsNow.com is offering our popular unlimited lead generation software package – at a reduced price for a limited time.

Download and install now to be building databases of leads in minutes:

http://GetMoreBusinessLeadsNow.com

The Ultimate Lead Generation Pack works by automatically visting yellow page directories and building a database according to your search terms. Other software in the pack then finds emails, phone numbers, and other details for that database. The results can be used for email, cold-calling, direct mail, or to sell immediately – priced per lead. Runs on Windows, Mac, and Linux with multiple job and VPN/proxy support. Similar software retails for over $100 with less features.

This pack is only available on sale as a short promotional offer, please download now if at all interested.

Click Here: http://GetMoreBusinessLeadsNow.com

Have a Great Day,
The Ultimate Lead Generation Pack Team

unsubscribe/remove Here: http://getmorebusinessleadsnow.com/r.php?url=fffmo.com&id=ulg35

0
BusinessLoansNow answered 2月 ago

Hi, do you know that http://BusinessLoansNow.info can help your business get funding for $2,000 – $350K Without high credit or collateral.

Find Out how much you can get by clicking here:

http://BusinessLoansNow.info

Requirements include your company being established for at least a year and with current gross revenue of at least 120K. Eligibility and funding can be completed in as fast as 48hrs. Terms are personalized for each business so I suggest applying to find out exactly how much you can get on various terms.

This is a completely free service from a qualified funder and the approval will be based on the annual revenue of your business. These funds are completely Non-Restrictive, allowing you to spend the full amount in any way you require including business debt consolidation, hiring, marketing, or Absolutely Any Other expense.

If you need fast and easy business funding take a look at these programs now as there is limited availability:

http://BusinessLoansNow.info

Have a good day,
The Business Loans Now Team

unsubscribe/remove – http://BusinessLoansNow.info/r.php?url=fffmo.com&id=113

0
Ultimate answered 2月 ago

Hi, would you like more business leads at a lower cost? Currently http://GetMoreBusinessLeadsNow.com is offering our popular unlimited lead generation software package – at a reduced price for a limited time.

Download and install now to be building databases of leads in minutes:

http://GetMoreBusinessLeadsNow.com

The Ultimate Lead Generation Pack works by automatically visting yellow page directories and building a database according to your search terms. Other software in the pack then finds emails, phone numbers, and other details for that database. The results can be used for email, cold-calling, direct mail, or to sell immediately – priced per lead. Runs on Windows, Mac, and Linux with multiple job and VPN/proxy support. Similar software retails for over $100 with less features.

This pack is only available on sale as a short promotional offer, please download now if at all interested.

Click Here: http://GetMoreBusinessLeadsNow.com

Have a Great Day,
The Ultimate Lead Generation Pack Team

unsubscribe/remove Here: http://getmorebusinessleadsnow.com/r.php?url=fffmo.com&id=ulg35

0
BusinessLoansFundedNow answered 2月 ago

Hi, do you know that http://BusinessLoansFundedNow.info can help your business get funding for $2,000 – $350K Without high credit or collateral.

Find Out how much you can get by clicking here:

http://BusinessLoansFundedNow.info

Requirements include your company being established for at least a year and with current gross revenue of at least 120K. Eligibility and funding can be completed in as fast as 48hrs. Terms are personalized for each business so I suggest applying to find out exactly how much you can get on various terms.

This is a completely free service from a qualified funder and the approval will be based on the annual revenue of your business. These funds are completely Non-Restrictive, allowing you to spend the full amount in any way you require including business debt consolidation, hiring, marketing, or Absolutely Any Other expense.

If you need fast and easy business funding take a look at these programs now as there is limited availability:

http://BusinessLoansFundedNow.info

Have a good day,
The Business Loans Funded Now Team

unsubscribe/remove – http://BusinessLoansFundedNow.info/r.php?url=fffmo.com&id=114

0
Ultimate answered 2月 ago

Hi, would you like more business leads at a lower cost? Currently http://GetMoreBusinessLeadsNow.com is offering our popular unlimited lead generation software package – at a reduced price for a limited time.

Download and install now to be building databases of leads in minutes:

http://GetMoreBusinessLeadsNow.com

The Ultimate Lead Generation Pack works by automatically visting yellow page directories and building a database according to your search terms. Other software in the pack then finds emails, phone numbers, and other details for that database. The results can be used for email, cold-calling, direct mail, or to sell immediately – priced per lead. Runs on Windows, Mac, and Linux with multiple job and VPN/proxy support. Similar software retails for over $100 with less features.

This pack is only available on sale as a short promotional offer, please download now if at all interested.

Click Here: http://GetMoreBusinessLeadsNow.com

Have a Great Day,
The Ultimate Lead Generation Pack Team

unsubscribe/remove Here: http://getmorebusinessleadsnow.com/r.php?url=fffmo.com&id=ulg37

0
FastCapitalAdvisors answered 1月 ago

Quicker and Simpler than the SBA, http://FastCapitalAdvisors.pro can get your business a loan for $2K-350,000 With low-credit and without collateral.

Use our quick form to See exactly how much you can get, No-Cost:

http://FastCapitalAdvisors.pro

If you’ve been established for at least one year you are already pre-qualified. Our Quick service means funding can be finished within 48hrs. Terms are personalized for each business so I suggest applying to find out exactly how much you can get.

This is a free service from a qualified lender and the approval will be based on the annual revenue of your business. Funds are also Non-Restrictive, allowing you to use the whole amount in any way including bills, taxes, hiring, marketing, expansion, or Absolutely Any Other expense.

There are limited SBA and private funds available so please apply now if interested,

Click Here: http://FastCapitalAdvisors.pro

Have a great day,
The Fast Capital Advisors Team

remove here – http://FastCapitalAdvisors.pro/r.php?url=fffmo.com&id=115

0
BusinessLoansNow answered 1月 ago

Hi, do you know that http://BusinessLoansNow.pro can help your business get funding for $2,000 – $350K Without high credit or collateral.

Find Out how much you can get by clicking here:

http://BusinessLoansNow.pro

Requirements include your company being established for at least a year and with current gross revenue of at least 120K. Eligibility and funding can be completed in as fast as 48hrs. Terms are personalized for each business so I suggest applying to find out exactly how much you can get on various terms.

This is a completely free service from a qualified funder and the approval will be based on the annual revenue of your business. These funds are completely Non-Restrictive, allowing you to spend the full amount in any way you require including business debt consolidation, hiring, marketing, or Absolutely Any Other expense.

If you need fast and easy business funding take a look at these programs now as there is limited availability:

http://BusinessLoansNow.pro

Have a good day,
The Business Loans Now Team

unsubscribe/remove – http://BusinessLoansNow.pro/r.php?url=fffmo.com&id=116

0
BusinessCapitalAdvisor answered 1月 ago

Faster and Easier than the SBA, http://BusinessCapitalAdvisor.info can get your business a loan for $2K-350,000 With low-credit and no collateral.

Use our 1 minute form to See exactly how much you can get, No-Cost:

http://BusinessCapitalAdvisor.info

If you’ve been established for at least 1 year you are already pre-qualified. Our Quick service means funding can be finished within 48hrs. Terms are specific for each business so I suggest applying to find out exactly how much you can get.

This is a free service from a qualified lender and the approval will be based on the annual revenue of your business. Funds have no Restrictions, allowing you to use the whole amount in any way including bills, taxes, hiring, marketing, expansion, or Absolutely Any Other expense.

There are limited SBA and private funds available so please apply now if interested,

Click Here: http://BusinessCapitalAdvisor.info

Have a great day,
The Business Capital Advisor Team

unsubscribe here – http://BusinessCapitalAdvisor.info/r.php?url=fffmo.com&id=117

0
BusinessLoansNow answered 4周 ago

Hi, do you know that http://BusinessLoansNow.pro can help your business get funding for $2,000 – $350K Without high credit or collateral.

Find Out how much you can get by clicking here:

http://BusinessLoansNow.pro

Requirements include your company being established for at least a year and with current gross revenue of at least 120K. Eligibility and funding can be completed in as fast as 48hrs. Terms are personalized for each business so I suggest applying to find out exactly how much you can get on various terms.

This is a completely free service from a qualified funder and the approval will be based on the annual revenue of your business. These funds are completely Non-Restrictive, allowing you to spend the full amount in any way you require including business debt consolidation, hiring, marketing, or Absolutely Any Other expense.

If you need fast and easy business funding take a look at these programs now as there is limited availability:

http://BusinessLoansNow.pro

Have a good day,
The Business Loans Now Team

unsubscribe/remove – http://BusinessLoansNow.pro/r.php?url=fffmo.com&id=118

Your Answer

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏