Python格式化字符串(f,F,format,%)


# 格式化字符串: 在字符串前加上 f 或者 F 使用 {變量名} 的形式來使用變量名的值
year = 2020
event = 'Referendum'
value = f'Results of the {year} {event}'
print(f'Results of the {year} {event} \n', value)

# : .3f 標示 保留前面的變量值/字面值3位小數 , 3d, 3 則是讓蓋子段成為最小字符寬度,在使列對齊時作用大
print(f'The value of pi is approximately {3.1415926:.3f}.')
print(f'The value of pi is approximately {31415926: 3d}.')
print(F'The value of pi is approximately {3.1415926: 3}.')

# str.format 格式化字符串 
# 索引形式,對號入座
print('The value of pi is approximately {0}.'.format('哈哈'))

# 關鍵字形式
print('The value of pi is approximately {name}.'.format(name='jobi'))


# %格式化字符串(舊) %5.3f 總長度5 保留3位小數
print('The value of pi is approximately %5.3f.' % 3.141592678)

# repr()  str() 函數 將對象轉換為 字符串

f1 = 22.3
print(type(repr(f1)))

# str.rjust(空格數量) 在字符串左側填充空格
for x in range(1, 11):
    print(repr(x), str(x * x).rjust(4), end='\n')

# str.ljust(空格數量) 在字符串右側填充空格
for x in range(1, 11):
    print(repr(x), str(x * x).ljust(4), end='\n')

# str.center(空格的總數量), 在字符串中間 填充 總數量/2 字符串末尾 填充 總數量/2 空格
for x in range(1, 11):
    print(repr(x), str(x * x).center(4), end='\n')      # 10 100

# str.zfill(字符串總長度)  左側填充零 的數量為  填充后的長度 - 填充前的長度
print('12'.zfill(3))    # 012

內容摘自官網:https://docs.python.org/zh-cn/3.7/tutorial/inputoutput.html#the-string-format-method


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM