2014-09-21 131 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

相關問題