【问题标题】:How to put a multi-row statement string into a variable? [duplicate]如何将多行语句字符串放入变量中? [复制]
【发布时间】:2019-09-10 08:03:53
【问题描述】:

我想将一个长字符串(特别是 SQL 查询)存储到一个变量中,我希望将其写入更多行以提高可读性。

如果这很重要的话,我正在 Python 3.5 (Anaconda) 上使用 Jupyter notebook。

我试过了:

# SQL query

query = "
SELECT
 Sued 
,ApplicationNumber_Primary
--,ApprovedLoanAmount, ApprovedLoanDuration, ApprovedMonthlyPayment, 
,RequiredLoanDuration, RequiredMonthlyPaymentAmount, RequiredPaidAmount, RequiredCoefficientK1
,ClientFreeSources, ClientTotalIncome, ClientNetIncome, ClientTotalExpenditures 
,ClientAgeToApplicationDate, ClientFamilyStatusID, ClientEmploymentDuration, CreditExposure
,CalendarQuarter, MonthOfYear, WeekOfYear, DayOfMonth, DayOfWeek, RegionID, DistrictID, ZIPcodeID 

FROM 
dbo.vRisk
GO
"

...它不会按照我的意愿将字符串存储到变量中。

我们将不胜感激。

【问题讨论】:

  • 使用'''(三引号)而不是双引号
  • 当然!我以为我会将该语句注释掉,但这显然不适用于将其放在变量中。

标签: python python-3.x


【解决方案1】:

尝试使用三引号:

query = """
SELECT
 Sued 
,ApplicationNumber_Primary
--,ApprovedLoanAmount, ApprovedLoanDuration, ApprovedMonthlyPayment, 
,RequiredLoanDuration, RequiredMonthlyPaymentAmount, RequiredPaidAmount, RequiredCoefficientK1
,ClientFreeSources, ClientTotalIncome, ClientNetIncome, ClientTotalExpenditures 
,ClientAgeToApplicationDate, ClientFamilyStatusID, ClientEmploymentDuration, CreditExposure
,CalendarQuarter, MonthOfYear, WeekOfYear, DayOfMonth, DayOfWeek, RegionID, DistrictID, ZIPcodeID 

FROM 
dbo.vRisk
GO
"""

【讨论】:

    【解决方案2】:

    使用多行字符串或在其中穿插'\n':

    this_is_a_multiline_string = """
    
    tata
    
    """
    

    this_as_well = '''
    
    tata
    
    '''
    

    and_this = "\ntata\n"
    

    Python.org string documentation


    and_like_so = ("Some string"      # no space after
                   "that spans lots"  # no space after
                   "of lines" )       # results in 'Some stringthat spans lotsof lines'
    

    (最后一个来源:https://stackoverflow.com/a/10660443/7505395

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 2014-09-30
      • 2011-12-09
      • 2017-09-08
      • 2020-04-29
      • 2016-09-21
      相关资源
      最近更新 更多