如何将多行语句字符串放入变量?

时间:2019-04-20 09:39:43

标签: python python-3.x

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

如果这很重要,我正在Python 3.5(Anaconda)上使用Jupyter笔记本。

我尝试过:

# 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
"

...如我所愿,它不会将字符串存储到变量中。

我们将不胜感激。

2 个答案:

答案 0 :(得分: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
"""

答案 1 :(得分:0)

使用多行字符串或在其中插入'\ 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