python - 你如何检查用户输入python中字符串后面的整数是什么?
问题描述
我正在开发一个基于 Python 经济文本的游戏。用户有他们的钱包和银行余额。为了让用户将钱从他们的钱包存入他们的银行,我希望他们输入
pls dep x
x 是一个整数。在我的游戏循环中,我放下
if 'pls dep ' in type or 'pls deposit ' in type:
?
在循环中,我将类型定义为
type = input('> ')
并且循环检查玩家是否通过执行调用任何命令
if type == 'a command':
我遇到的问题是我不知道如何检查之后放入的整数
pls dep (integer)
用文字来写我想让它像
if player called the command 'pls dep ', check what the number is after 'pls dep '
and if player has that much amount of money, subtract the x from their wallet and
Add x to their bank balance.
钱包是
player_money = 0
玩家银行余额为
player_bank_money = 0
任何人都可以帮助我如何编码(化)我上面所说的吗?
解决方案
不要使用内置名称作为变量。type
是一个内置名称。
使用.split
(蒂姆罗伯茨在评论中所说的):
command = input('> ')
if 'pls dep ' in command or 'pls deposit ' in command:
print(f"You deposited {command.split()[2]}")
使用.strip
(不要这样做,这不是一个很好的用法strip
):
command = input('> ')
if 'pls dep ' in command or 'pls deposit ' in command:
print(f"You deposited {command.strip('pls dep ').strip('pls deposit ')}")
实现货币变量(最终代码):
player_money = 0
player_bank_money = 0
command = input('> ')
if 'pls dep ' in command or 'pls deposit ' in command:
dep_money = int(command.split()[2])
player_money -= dep_money
player_bank_money += dep_money
print(f"You have ${player_money} in your wallet. You have ${player_bank_money} is your bank.")
此外,如果您不希望命令区分大小写,command.lower()
请在 if 条件之前使用:。
推荐阅读
- webpack - echarts - 覆盖时间刻度组件
- javascript - Uncaught SyntaxError: missing ) 在 html 行中的参数列表抛出错误之后
- php - Symfony PHP - 在另一个服务中使用服务
- algorithm - 用于 BST 级别顺序遍历的惯用 Kotlin
- python - 如何将matplotlib对象传递/返回python中的函数
- angularjs - 更新调用丢失配置变量中的日期值
- c# - 在一个场景中更改一个对象会在 2 中更改它
- postgresql-9.3 - 为什么同一列上的索引大小不同
- c++ - 编码大于原文:How to take a strings of zero and one and write them as actual bytes to file
- javascript - 如何将日期时间与 10 分钟进行比较?