2016-04-03 62 views
1

我將兩個整數的字符串轉換爲元組。我需要確保我的字符串使用逗號格式化爲"<int1>,<int2>",並且沒有多餘的空格。我知道isdigit()可以用來檢查一個給定的字符串是否只包含數字。但是,這不會解決所需的逗號和空格。檢查Python中「<int1>,<int2>」的確切字符串

這裏是我的代碼將字符串轉換爲整數的元組:

s1 = "12,24" 
string_li = s1.split(',') 
num_li = [int(x) for x in string_li] 
num_tuple = tuple(num_li) 

有人建議正則表達式可以在這裏使用。我將如何實現這個if/else語句?這是行得通的,但似乎並不正確:

import re 
s1 = '12,24' 
if re.match("^\d+,\d+$",s1) is not None: 
    print("pass") 

你能指出我在正確的方向嗎?

+1

該代碼看起來不錯。如果你認爲可能有不好的輸入,你可以把你的處理放到一個'try'塊中並且捕獲相關的異常。 – TigerhawkT3

回答

1

聽起來像正規表達式的工作。

import re 
re.match("^\d+,\d+$", some_string) 
  • ^比賽開始字符串匹配
  • \d+一個或多個數字
  • ,逗號文字
  • $匹配字符串的結尾

一些測試用例比賽:

assert re.match("^\d+,\d+$", "123,123") 
assert not re.match("^\d+,\d+$", "123,123 ") # trailing whitespace 
assert not re.match("^\d+,\d+$", " 123,123") # leading whitespace 
assert not re.match("^\d+,\d+$", "a,b") # not digits 
assert not re.match("^\d+,\d+$", "-1,3") # minus sign is invalid 

re.match返回值是MatchObjectNone,好在它們表現爲預計在布爾上下文 - MatchObject是truthy和None是falsy,如可以看到的是斷言以上陳述。

+0

不,它可以是['MatchObject'](https://docs.python.org/2/library/re.html#re.MatchObject)或'None',幸運的是它們的行爲與布爾上下文中的預期相同 - MatchObject是truthy和'None'是虛假的。 –

+0

不,它是「如果匹配」和「如果不匹配」,顯然你需要使用完整的語句,而不是如果匹配 – Keatinge

+0

'如果re.match(「^ \ d +,\ d + $」,some_string):'如預期。 –

相關問題