首页 > 解决方案 > 你如何检查用户输入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

任何人都可以帮助我如何编码(化)我上面所说的吗?

标签: python

解决方案


不要使用内置名称作为变量。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 条件之前使用:。


推荐阅读