如何将多行语句字符串放入变量中? [复制]
Posted
技术标签:
【中文标题】如何将多行语句字符串放入变量中? [复制]【英文标题】: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
"
...它不会按照我的意愿将字符串存储到变量中。
我们将不胜感激。
【问题讨论】:
使用'''
(三引号)而不是双引号
当然!我以为我会将该语句注释掉,但这显然不适用于将其放在变量中。
【参考方案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://***.com/a/10660443/7505395)
【讨论】:
以上是关于如何将多行语句字符串放入变量中? [复制]的主要内容,如果未能解决你的问题,请参考以下文章