[英]If string ends and starts with "*" in Python
是否有一個簡單的 if 語句來解決這個問題? 到目前為止,第一個塊是我的代碼,第二個塊是我希望打印的 boolean output。
if string.startswith("*") and string.endswith("*"):
return True
else:
return False
print(string_startend_function('*JohnDoe*')) # True (This answer my code can achieve)
print(string_startend_function('*')) # False (This answer my code can't achieve)
如果 startswith * 和 endswith * 是相同的單數 *,我需要我的代碼顯示 False,是否有辦法通過在 if 語句后添加 elif 語句來實現這一點?
由於'*'
是string
的唯一可能值,其中string.startswith("*") and string.endswith("*")
為True
並且 function 應返回False
,您可以簡單地添加不等式測試以確保string
實際上不是'*'
:
return string != '*' and string.startswith("*") and string.endswith("*")
您還可以使用像^\*.*\*$
這樣的正則表達式,意思是“開始,文字*
,更多內容,文字*
,結束”
>>> import re
>>> re.match(r"^\*.*\*$", "*") is not None
False
>>> re.match(r"^\*.*\*$", "*JohnDoe*") is not None
True
>>> re.match(r"^\*.*\*$", "*invalid") is not None
False
我想到的解決方案是正則表達式,但是:
對於短代碼,這段代碼怎么樣?
return len(s) > 1 and s[0] + s[-1] == "**"
不使用startWith
或endWith
方法:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.