“+\”是什么意思?Python生成请求Xm

2024-09-30 03:25:38 发布

您现在位置:Python中文网/ 问答频道 /正文

每行的末尾都有一个“+\”:

def buildRequestXml(detailLevel, viewAllNodes):
    requestXml = "<?xml version='1.0' encoding='utf-8'?>"+\
              "<AddItemRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">"+\
              "<RequesterCredentials><eBayAuthToken>" + userToken + "</eBayAuthToken></RequesterCredentials>"

    if (detailLevel != ""):
        requestXml = requestXml + "<DetailLevel>" + detailLevel + "</DetailLevel>"

    requestXml = requestXml + "<Item>"+\
                    "<BuyItNowPrice>10.0</BuyItNowPrice>"+\
                    "<Country>US</Country>"+\
                    "<Currency>USD</Currency>"+\
                    "<Description>This is a test.</Description>"+\
                    "<ListingDuration>Days_7</ListingDuration>"+\
                    "<Location>San Jose, CA</Location>"+\
                    "<PaymentMethods>PaymentSeeDescription</PaymentMethods>"+\
                    "<PrimaryCategory>"+\
                    "  <CategoryID>357</CategoryID>"+\
                    "</PrimaryCategory>"+\
                    "<Quantity>1</Quantity>"+\
                    "<StartPrice>1.0</StartPrice>"+\
                    "<ShippingTermsInDescription>True</ShippingTermsInDescription>"+\
                    "<Title>Test item title</Title>"+\
                "</Item>"+\
              "</AddItemRequest>"
    return requestXml

Tags: locationdescriptionitemcountrycurrencyprimarycategoryrequestercredentialsebayauthtoken
3条回答

\是一个行延续字符,意味着下一行是当前行的延续

但是,根据PEP-0008样式指南,最好使用括号隐式继续:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.


用括号代替\

requestXml = (requestXml + "<Item>"+
    "<BuyItNowPrice>10.0</BuyItNowPrice>"+
    "<Country>US</Country>"+
    "<Currency>USD</Currency>"+
    "<Description>This is a test.</Description>"+
    "<ListingDuration>Days_7</ListingDuration>"+
    "<Location>San Jose, CA</Location>"+
    "<PaymentMethods>PaymentSeeDescription</PaymentMethods>"+
    "<PrimaryCategory>"+
    "  <CategoryID>357</CategoryID>"+
    "</PrimaryCategory>"+
    "<Quantity>1</Quantity>"+
    "<StartPrice>1.0</StartPrice>"+
    "<ShippingTermsInDescription>True</ShippingTermsInDescription>"+
    "<Title>Test item title</Title>"+
  "</Item>"+
"</AddItemRequest>")

通过将表达式包装在括号中,Python知道如何继续下一行。你知道吗

\表示行的延续。你知道吗

这是一个行延拓运算符。基本上,它是对不可见的换行符进行转义,迫使Python将所有这些都视为一行。你知道吗

例如

somevar = 'foo'+\
    'bar'

与相同

somevar = 'foo'+'bar'

相关问题 更多 >

    热门问题