0

当询问他们的储蓄和存款时,我试图在用户输入中添加一个美元符号(“$”)。在我的脚本结束时,我正在创建一个包含所有信息的文本文件,但我希望在创建文件时数字前面有符号。

savings =  int(input("How much money do you have in your savings: ")
deposits = int(input("How much money do you put in deposits: ") 

from tabulate import tabulate
table = tabulate([["Name", "Last", "Age", "Company", "Hourly Rate", "Occupation", "Savings", "Deposits"],
[(name), (last_name), (age), (company), (hourly_rate), (occupation), (savings, + "$"), (deposits)]], headers = "firstrow")

我已将 +"$" 添加到 Savings 变量中,因为我认为这会起作用,但后来我会收到此错误:

TypeError: bad operand type for unary +: 'str'

所以总而言之,即使创建了文本文件,我也只希望它具有美元符号,因为这是它现在看起来的示例:

储蓄存款


9000 900 <----缺少美元符号

我希望这是有道理的。谢谢你。

4

5 回答 5

2

看看你是否会使用int然后你不能将钱与美元符号连接起来,因为'$'是一个字符串。你可以这样做:

# Trying to make it have a special character when file is printed such as "$" Example: $2600
savings = '$' + input("How much money do you have in your savings: ")
deposits = '$' + input("How much money do you put in deposits: ")
于 2021-07-28T06:32:49.490 回答
0

When you print the variables, you can type cast them into string and append $ at the start.

print("$"+str(savings))
print("$"+str(deposits))
于 2021-07-28T06:30:23.430 回答
0

好吧,这很容易

对于 Python3,您可以简单地使用F Strings

savings = int(input("How much money do you have in your savings: "))
deposits = int(input("How much money do you put in deposits: "))
print(f"₹ {savings}")
print(f"₹ {deposits}")

阅读更多关于F Strings这里

于 2021-07-28T06:35:11.987 回答
0

您可以使用该%标志。
% 符号后跟一个指向数据类型的字符。如果是整数,请使用 d。

%s -> String
$d -> Int
%f -> Float
savings = int(input("How much money do you have in your savings: "))
deposits = int(input("How much money do you put in deposits: "))

savings = "$%d" % savings
deposits = "$%d" % deposits
于 2021-07-28T06:35:32.100 回答
0

你可以使用f-strings.

如果您只想$在前面打印,

savings = int(input("How much money do you have in your savings: "))
deposits = int(input("How much money do you put in deposits: "))

print(f'Savings: ${savings}')
print(f'Deposits: ${deposits}')
Sample Output:

Savings: $51
Deposits: $25

如果你想保存savingsand前面deposits有一个,那么$

savings = '$' + input("How much money do you have in your savings: ")
deposits = '$'+ input("How much money do you put in deposits: ")

savings并且deposits现在将是字符串而不是int

于 2021-07-28T06:32:03.100 回答