Python的String字串 format() 語法,是一個非常有用的功能,可以讓你的程式更有效率,讓你的程式更容易閱讀與維護。

String字串 format() 語法可以讓你將字串中的變數替換成你想要的值,例如:

name = 'John'
print('Hello, {}'.format(name))

上面的程式碼會輸出:

Hello, John

你也可以使用多個變數,例如:

name = 'John'
age = 20
print('{} is {} years old'.format(name, age))

上面的程式碼會輸出:

John is 20 years old

你也可以使用索引來指定變數的位置,例如:

name = 'John'
age = 20
print('{1} is {0} years old'.format(age, name))

上面的程式碼會輸出:

John is 20 years old

你也可以使用字典來指定變數的位置,例如:

person = {'name': 'John', 'age': 20}
print('{name} is {age} years old'.format(**person))

上面的程式碼會輸出:

John is 20 years old

學習Python String字串 format() 語法,讓你的程式更有效率!

Python的String字串 format() 語法,是一個非常有用的功能,可以讓你的程式更有效率,讓你的程式更容易閱讀與維護。

String字串 format() 語法可以讓你將字串中的變數替換成你想要的值,例如:

name = 'John'
print('Hello, {name}'.format(name))

上面的程式碼會輸出:

Hello, John

你也可以使用多個變數,例如:

name = 'John'
age = 20
print('{name} is {age} years old'.format(name, age))

上面的程式碼會輸出:

John is 20 years old

你也可以使用索引來指定變數的位置,例如:

name = 'John'
age = 20
print('{1} is {0} years old'.format(age, name))

上面的程式碼會輸出:

John is 20 years old

你也可以使用字典來指定變數的位置,例如:

person = {'name': 'John', 'age': 20}
print('{name} is {age} years old'.format(**person))

上面的程式碼會輸出:

John is 20 years old

學習Python String字串 format() 語法,讓你的程式更有效率!

Categorized in: