![](/img/trans.png)
[英]How can i use “str.find” (python) to locate the next character after a space or “ ”?
[英]Use an if with a python str.find()
我正在嘗試使用Python解析以下字符串: At 11:00 am EST, no delay, 7 lane(s) open
。 我需要閱讀它,看看它是否包含no delay
的字符串。 我使用以下內容對其進行了解析: contents_of_tunnel.find("no delay")
。
運行良好。 但是當我在if/else
使用它時,如下所示:
>>> if contents_of_tunnel.find("no delay") == True:
... print 1
... else:
... print 0
...
0
歸零。 為什么是這樣? 我相信問題在於第一行,就像這樣: >>> if contents_of_tunnel...
謝謝您的幫助。
也許您想要這樣的東西:
if 'no delay' in contents_of_tunnel: print 1
else: print 0
要不就
print 1 if 'no delay' in contents_of_tunnel else 0
find(...)
S.find(sub [,start [,end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
這將打印1的唯一方法是,如果contents_of_tunnel
以“ no delay”開頭,因為返回的索引將為0。-1的計算結果為True
。
您應該使用:
if contents_of_tunnel.find("no delay") != -1:
要么
if "no delay" in contents_of_tunnel:
要么
try:
index = contents_of_tunnel.index("no delay")
# substring found
except ValueError:
# substring not found
原因是contents_of_tunnel.find("no delay")
返回一個數字。 因此,請使用!= -1
而不是使用== True
。 這樣,它將完成您的預期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.