如何获取输入字符串的某些部分?

2024-09-29 21:47:04 发布

您现在位置:Python中文网/ 问答频道 /正文

主要是让用户输入一些数据

def getmonsterData():
  monster1 = raw_input("Enter the Monster Affinity|HP|AD> ")
  x = monster1.index('|');
  affinityType = monster1[0:x]
  printNow(affinitytype)

我能够制作一个变量来存储怪物的亲缘关系,所以在打印时它会列出用户输入的内容(即:火/地球),但我不知道如何抓取和创建一个类似的惠普和广告

这将打印任何我列出的怪物1的亲和力,如火。这一切都很好, 但是当我不太确定如何使用Jython/Python拼接字符串时。。可能是这样的

HP = monster1[affinityType+1:x] ? not too sure how to do this

类似地,我需要得到最后一个变量AD,如果我得到HP变量,我相信我可以做到

 y = len(monster1)
 AD = monster1[x+1:y]

任何关于这方面的意见都会有帮助:)谢谢


Tags: the数据用户inputrawdefadhp
1条回答
网友
1楼 · 发布于 2024-09-29 21:47:04

可以使用拆分:

>>> aff,HP,AD = raw_input("Enter the Monster Affinity|HP|AD> ").split('|')
Enter the Monster Affinity|HP|AD> a|11|22
>>> aff
'a'
>>> HP
'11'
>>> AD
'22'

但是如果您想使用index,可以使用start参数(S.index(sub [,start [,end]]) -> int

>>> monster =  raw_input("Enter the Monster Affinity|HP|AD> ")
Enter the Monster Affinity|HP|AD> a|11|22
>>> x = monster.index('|')
>>> monster[:x]
'a'
>>> y = monster.index('|',x+1)
>>> monster[x+1:y]
'11'
>>> monster[y+1:]
'22'

相关问题 更多 >

    热门问题