社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何将符号添加到用户输入(Python)

Amar Mujak • 3 年前 • 1415 次点击  

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

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<----丢失的美元符号

我希望这是有道理的。非常感谢。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131170
 
1415 次点击  
文章 [ 5 ]  |  最新文章 3 年前
Hailey
Reply   •   1 楼
Hailey    4 年前

你可以使用 % 签名
%符号后面跟着一个指向数据类型的字符。如果是整数,则使用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
DEVLOPR
Reply   •   2 楼
DEVLOPR    4 年前

这很容易做到

对于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 Here

Ram
Reply   •   3 楼
Ram    4 年前

你可以用 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

如果你想拯救世界 savings deposits 用一个 $ 那么在前面

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

节省物 存款 现在将是字符串而不是 int .

George
Reply   •   4 楼
George    4 年前

打印变量时,可以将它们转换为字符串,并在开头追加$。

print("$"+str(savings))
print("$"+str(deposits))
Abhyuday Vaish
Reply   •   5 楼
Abhyuday Vaish    4 年前

看看你是否会使用 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: ")