Python字串相加以及字串格式化

來源:互聯網
上載者:User

標籤:python字串   name   IV   記憶體   %x   format   orm   bsp   shu   

1、在Python中字串a佔用一塊記憶體位址,字串b也佔用一塊記憶體位址,當字串a+b時,又會在記憶體空間中開闢一塊新的地址用來存放a+b。

  a 地址一

  b 地址二

  a+b 地址三

  因此記憶體中就佔了三份空間,對記憶體消耗是很大的因此盡量使用字串格式化來進行字元拼接。

2、字串格式化

  a、常見的預留位置
    %d:整數
    %f:浮點數
    %s:字串
    %x:十六進位整數
  b、其中,格式化整數和浮點數還可以指定是否補0和整數與小數的位元:

print(‘%2d-%02d‘%(3,1)):‘3-01‘print(‘%.2f‘ %3.1415926):3.14

  c、用%%來表示一個%

print(‘wohaoshuai%%%s‘ %(‘5‘))

3、format字串格式化

i1 = "i am {},age {} ,{}".format(‘cairui‘,18,‘kk‘)print(i1)  i am cairui,age 18 ,kki1 = "i am {0},age {1} ,{0}".format(‘cairui‘,18)print(i1)  i am cairui,age 18 ,cairuii1 = "i am {name},age {age} ,{name}".format(name=‘cairui‘,age=18)print(i1)  i am cairui,age 18 ,cairuii1 = "i am {:s},age {:d} ,{:f}".format(‘cairui‘,18,6.1)print(i1)  i am cairui,age 18 ,6.100000 

 

Python字串相加以及字串格式化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.