這個問題在這里已經有了答案: 如何連接 str 和 int 物件? (1 個回答) 如何將變數的值放入字串中(將其插入字串中)? (9 個回答) 19 小時前關閉。
代碼
character_name = "Tom"
character_age = "50"
is_male = False
print("There once was a man named " character_name ", ").
print("he was " character_age " years old. ")
character_name = "Mike"
print("He really liked the name " character_name ",")
print("but didn't like being " character_age ".")
我將其更改為
character_name = "Tom"
character_age = 50
is_male = False
print("There once was a man named " character_name ", ").
print("he was " character_age " years old. ")
character_name = "Mike"
print("He really liked the name " character_name ",")
print("but didn't like being " character_age ".")
錯誤代碼
/Users/praisekittens/PycharmProjects/Proj3/venv/bin/python /Users/praisekittens/PycharmProjects/Proj3/George.py
There once was a man named Tom,
Traceback (most recent call last):
File "/Users/praisekittens/PycharmProjects/Proj3/George.py", line 5, in <module>
print("he was " character_age " years old. ")
TypeError: can only concatenate str (not "int") to str
Process finished with exit code 1
想法
我是編碼的新手,并且正在學習 freeCodeCamp.org 的 Youtube 上的一個四年前的教程,在這部分之前,一切都非常完美。在我看來,引號的洗掉導致了將 int 連接到 str 的問題。
當他拿走引??文時,我確實看到兩個 character_age 欄位都以黃色突出顯示,表示錯誤。從他說話的方式來看,他讓我覺得他能夠運行這段代碼并讓它作業。
問題
如果沒有 50 左右的引號,我的代碼可以作業嗎?
為什么他首先建議這樣做?我期待從分離 str 和 int 中獲得一些好處,結果卻遇到了這個有點令人沮喪的錯誤
什么是這種情況下使用的最佳代碼?
uj5u.com熱心網友回復:
str()
您可以使用在您的代碼中將整數轉換為字串:
print("he was " str(character_age) " years old. ")
print("but didn't like being " str(character_age) ".")
作為額外提示,您還可以使用 python f 字串進行列印格式化。這些是在 python 3.6 中引入的。這是一個例子。
print(f'he was {character_age} years old. '
這使您無需一直使用字串連接即可進行格式化。干杯。
uj5u.com熱心網友回復:
print(f"There once was a man named {character_name}, he was {character_age} years old.")
character_name = "Mike"
print(f"He really liked the name {character_name},but didn't like being {character_age}.")
您可以嘗試這樣的事情,因此字符年齡可以是字串或整數('15',或 15)。
uj5u.com熱心網友回復:
Can my code work without the quotations around the 50?
是的。您只需使用str(your_variable)或 f'' 字串將變數轉換為不同的型別。
print(f"He really liked the name {character_name}, but didn't like being {character_age}.)"
Why is he suggesting to do this in the first place?
正如這里提到的, Python 是非常型別化的,并且會避免進行隱式型別轉換。
What is the best code to use for this scenario?
這取決于你。您可以通過三個選項來解決此問題:
- 在連接之前將整數變數轉換為字串
- 在 print() 陳述句中使用逗號連接
- 使用 f'' 字串(f 字串)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/510261.html
