簡體   English   中英

處理可能引發錯誤的條件語句的最pythonic 方法是什么?

[英]What is the most pythonic way to deal with a conditional statement that may raise an error?

處理可能引發錯誤的條件語句的最pythonic 方法是什么? 例如:

if string[0] = "#":

如果給定長度為 0 的字符串,上述語句將導致 IndexError。

我想像這樣的東西:

if try testFunction() (except: pass):

……但我知道那行不通。 所以我該怎么做?

注意:這個問題有很多解決方案。 例如,我可以將 if 語句放在第二個 if 語句中……但這並不優雅。 我特別在尋找最 Pythonic 的解決方案。

您必須將整個if語句放在try..except塊中:

try:
    if string[0] == "#":
        # block executed when true
except IndexError:
    # ..

但是有更好的選擇:

  • 首先提取那個字符:

     try: first = string[0] except IndexError: pass else: if first == '#': # ...
  • 首先測試字符串長度:

     if string and string[0] == '#':
  • 使用切片:

     if string[:1] == '#':

    如果string開頭為空,切片會產生一個空字符串。

  • 使用字符串方法:

     if string.startswith('#'):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM