[英]Check whether characters in a string are delimited by a space [Python]
假設我有一個字符串a = 31 4 5 + +
和一個字符串b = 31 4 5 ++
。 我需要檢查字符串中的所有數字和運算符是否由至少一個空格分隔。 因此,字符串 a 正確,字符串 b 不正確。 c = 31 4 5+ +
也是不正確的。 有沒有辦法檢查這個? 我想不出任何合理的東西。
您可以通過以下步驟進行檢查 -
.split()
將字符串分解為列表代碼片段:
def is_valid_string(st, delimiter = ' '):
lst = st.split(delimiter) # create list of chars separated by space
for item in lst:
if len(item) > 1 and not item.isdigit():
return False
return True
如果您正在考慮浮點數,您可以使用item.replace('.','',1).isdigit()
首先要做的是將字符串按空格拆分為“單詞”,因此類似於words = a.split()
(默認情況下split
的分隔符是空格,因此不需要參數)
我猜你只會使用整數或浮點數以及一組運算符,如加法、減法、乘法和除法,所以你可以做的一件事是檢查是否可以使用int
或float
將單詞轉換為數字,如果你不能,檢查這個詞是否在你的運營商集中,比如:
a = "31 4 5 + +"
operators = ["+", "-", "*", "/"]
# Every string is valid by default
valid = True
words = a.split() # ["31", "4", "5", "+", "+"]
for word in words:
# try to cast word into a number
try:
float(word)
except:
# if you can't, check if it's an operator
if word not in operators:
valid = False #if it's not, the string isn't valid
if valid:
print("String is valid")
else:
print("String is not valid")
方程和變量等更復雜的東西顯然更難編碼。
編輯:python 的isdigit()
檢查字符串是否為數字,它比用於轉換字符串的 try 塊更簡單,但它不檢查浮點數,這將是無效的。 (您仍然可以用數字替換小數點)
嘗試使用正則表達式^((\d+|[+*/-])(\s+|$))+$
。 它匹配更多或更多項目,每個項目要么是數字( \d+
)要么是運算符( [+*/-]
),后跟一個或多個空格( \s+
)或字符串結尾( $
)。 開頭的^
和結尾的 ( $
) 強制正則表達式匹配整個字符串。 例子:
>>> import re
>>> a = '31 4 5 + +'
>>> b = '31 4 5 ++'
>>> c = '31 4 5+ +'
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', a))
<re.Match object; span=(0, 10), match='31 4 5 + +'>
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', b))
None
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', c))
None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.