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

Python string formatting

編輯:Python

adopt % Format string

# coding:utf-8
if __name__ == '__main__':
''' Add a match to the string + % + The value to be matched Format string , When the number of values to be matched is greater than 1 when , You need to use the tuple format '''
print('%s Celebrate the new year in Shanghai ' % ' I ') # I spent the new year in Shanghai 
print('%s stay %s Celebrate the new year on the spot ' % (' I ', ' Shanghai ')) # I spent the new year in Shanghai 
print('%d year , I spent the new year in Shanghai ' % 2022) # 2022 year , I spent the new year in Shanghai 
print('%u year , I spent the new year in Shanghai ' % -2022) # -2022 year , I spent the new year in Shanghai 
print('%f year , I spent the new year in Shanghai ' % 2022) # -2022.000000 year , I spent the new year in Shanghai 
print('%c Chinese New Year in Shanghai ' % 'a') # a Chinese New Year in Shanghai 
print('%c Chinese New Year in Shanghai ' % ' I ') # I spent the new year in Shanghai 
print('%o' % 12) # 14
print('%x' % 30) # 1e
print('%e' % 100000000) # 1.000000e+08
Match symbol effect %s Universal talisman , Everything matches %d Match integer numbers %u Match unsigned integer numbers , But actually %d equally %f Match floating point type %c Match a character or a Chinese %o Match octal integer numbers %x Match hexadecimal integer numbers %e Match scientific notation

adopt string.format() format

# coding:utf-8
if __name__ == '__main__':
''' Use {} operator + string.format() Formatted string {} To specify the matching order , Included {0} On behalf of the match string.format() First parameter in If you don't specify , Use it directly {}, Match from left to right string.format() Parameters in '''
print(' today {0} stay {1} The Chinese New Year '.format(' I ', ' Shanghai ')) # Today I am in Shanghai for Chinese New Year 
print(' today {1} stay {0} The Chinese New Year '.format(' I ', ' Shanghai ')) # Today, Shanghai is celebrating Chinese New Year in my hometown 
print(' today {} stay {} The Chinese New Year '.format(' I ', ' Shanghai ')) # Today I am in Shanghai for Chinese New Year 

adopt f‘’ Formatted string

# coding:utf-8
if __name__ == '__main__':
''' adopt f'' + { Variable name } format This requires variable names to be declared in advance '''
name = ' I '
address = ' Shanghai '
print(f'{
name} In today's {
address} The Chinese New Year ') # I am in Shanghai for the Chinese New Year today 

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