2014-09-21 130 views
-2
import math 

x = raw_input("Enter your address") 

print ("The first number to the power of the second number in your address is", math.pow(

课程的第二个完整周刚刚结束,我遇到了麻烦,找出如何在字符串中找到特定的东西。 如果用户输入地址“1234地址” 我需要在math.pow中放置什么,以便知道如何查找数字1和2?如何查找给定字符串中的特定字符?

在类中唯一显示的是str.index(''),我只能用它来查找字符串中特定字符的位置。

我很快就有一项任务,很大程度上依赖于此,所以任何帮助将不胜感激。

编辑:为了澄清,我将如何让python在地址中查找地址中的第一个和第二个数字?

+1

你的意思是找到1和2哪里他们说谎或只是字符串的第一个和第二个字符? – Nabin 2014-09-21 10:04:51

+0

我刚刚重读了我写的东西,对不起:( 如何找到字符串中的第一个和第二个数字,他们所在的位置 如果地址是“地址2542”2和5是什么应该找到。 – AmandaZ 2014-09-21 10:07:30

回答

1

只需使用x.isdigit()来查找数字并将其插入列表中。然后用math.pow找到前两个的力量。

#!/usr/bin/python 
import math 

address = raw_input("Enter your address : ") 
digits = [] 

for c in address: 
    if c.isdigit(): 
     digits.append(c) 

if len(digits) >= 2: 
    print "The first number to the power of the second number in your address is : " 
    print math.pow(float(digits[0]), float(digits[1])) 
else: 
    print "Your address contains less than 2 numbers" 
0

由于字符串是Python中的迭代类型数据,您可以使用索引来访问字符串字符!像my_string[1]这给你第二个字符!然后用isdigit()函数可以检查它是否是数字!

演示:

>>> s='12erge' 
>>> s[1] 
'2' 
>>> s[1].isdigit() 
True 
>>> s[4] 
'g' 
>>> s[4].isdigit() 
False 

而且字符串中您可以使用[regex][1]re.search()功能查找号码:

>>> import re 
>>> s='my addres is thiss : whith this number 11243783' 
>>> m=re.search(r'\d+',s) 
>>> print m.group(0) 
11243783 
在此代码 r'\d+'

与LEN匹配所有的数字,一个正则表达式更比0,

1
import re 
numbers = re.findall(r'\d+',x) 
numbers[0][0:2] 

您需要导入正则表达式。它会更有用,因为您不知道字符串中数字的顺序。之后,您需要找到字符串中的所有数字。 '\ d +'将帮助获取字符串中的所有数字。然后,你需要做的就是取第一个元素,并从该字符串中取出前两个数字。

希望这会有所帮助。

+0

添加它的工作方式将有助于阿曼达,不是吗? – Llopis 2014-09-21 10:13:52

+1

仍在编辑答案.. – lakesh 2014-09-21 10:14:23

相关问题