![](/img/trans.png)
[英]Anyone can help me figure out why I got a wrong normal probability density figure with plot.hist function
[英]I'm trying something new with python but isn't working, can anyone help me figure out why the function only prints data[0]?
所以我想把一個字符串改成一個整數,然后讓控制台用正確的逗號打印數字,
所以字符串可以是“200萬”,但我希望控制台將 2,000,000 作為整數打印,包括逗號分隔符,到目前為止這是我的代碼;
def main():
print("Please enter a number using the word 'thousand' or 'million'.")
number = input("For example, 1 million or 1 thousand: ")
data = number.split(" ")
if data[1] == str.lower('thousand'):
data[1] = 000
reply = (int(data[0]) + data[1])
print(f"{reply:,}")
main()
但是當我運行代碼並輸入“2000”時,控制台只打印數字 2,沒有零或逗號,我哪里出錯了?
def main():
print("Please enter a number using the word 'thousand' or 'million'.")
number = input("For example, 1 million or 1 thousand: ")
data = number.split(" ")
if data[1] == str.lower('thousand'):
data[1] = ',000'
reply = ((data[0]) + data[1])
# print(f"{reply:,}")
print(reply)
main()
現在打印 0。 您必須將 000 添加為字符串。
或者
def main():
print("Please enter a number using the word 'thousand' or 'million'.")
number = input("For example, 1 million or 1 thousand: ")
data = number.split(" ")
if data[1] == str.lower('thousand'):
data[1] = '000'
reply = int(str(data[0])+data[1])
numbers = "{:,}".format(reply)
# print(f"{reply:,}")
print(numbers)
main()
def main():
print("Please enter a number using the word 'thousand' or 'million'.")
number = input("For example, 1 million or 1 thousand: ")
data = number.split(" ")
if data[1] == 'thousand':
data[1] = ',000'
reply = ((data[0]) + data[1])
# print(f"{reply:,}")
print(reply)
elif data[1] == str.lower('million'):
data[1] = ',000,000'
reply = ((data[0]) + data[1])
# print(f"{reply:,}")
print(reply)
main()
您可以將 data[1] 更改為帶逗號的字符串
你可以在你的 str 中替換它:
def main():
print("Please enter a number using the word 'thousand' or 'million'.")
number = input("For example, 1 million or 1 thousand: ")
str_number={
"thousand":"000",
"million":"000,000"
}
print(','.join([str_number[e] if e in str_number else e for e in number.split(' ')]))
main()
如果你想使用整數,你可以這樣做:
reply = int(data[0]) * 1000 # or 1000000 if "million"
我會使用與 Satyam Shankar 類似的方法,但也許使用字典來動態替換“百萬”或“千”為適當的字符串:
def main():
replacement = {"thousand":",000",\
"million" :",000,000"
}
print("Please enter a number using the word 'thousand' or 'million'.")
number = input("For example, 1 million or 1 thousand: ")
data = number.split(" ")
if data[1] == str.lower('thousand'):
data[1] = replacement[data[1]]
reply = ((data[0]) + data[1])
# print(f"{reply:,}")
print(reply)
main()
這種方法具有很強的可擴展性; 您可以通過擴展替換字典來添加使用“billion”、“trillion”等的能力。
在進一步擴展這一點時,想想如果用戶輸入,例如“12000”、“170 萬”或“200 萬 54.3 萬 819”,您可能想要什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.