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

Python Basics - string formatting

編輯:Python

There are three ways to format strings :

1、 Use placeholders % format , Original version

2、 Use str.format() format ,python2.6 Version to introduce

3、f-strings expression , Can parse any type of data , Render at run time , Performance ratio %,.format() Better .python3.6 Version to introduce

name = 'peter'
age = 20
# %s Formatted string ,%d Formatted integer
print('%s is %d years old' % (name, age))
# str.format() Three ways of writing , The parameter type is not limited , Number
print('{} is {} years old'.format(name, age))
print('{1} is {1} years old'.format(name, age))
print('{name} is {name} years old'.format(name='test', age=22))
# f-string Basic usage of expressions
print(f'{name} is {age} years old')
print(F'{name} is {age} years old')
# Analytic expression
print(f'{1 + 2}')
print(f'{2 * 4}')
# Parsing built-in functions
print(f'{name.upper()}')
# Attribute methods for parsing basic data types
list = ['hello', 'world']
print(f'{list[0]}')
------------------------------------------------
Running results :
peter is 20 years old
peter is 20 years old
20 is 20 years old
test is test years old
peter is 20 years old
peter is 20 years old
3
8
PETER
hello


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