如何编写多行字符串格式的函数?

时间:2019-04-23 23:23:10

标签: python string eval

我想编写一个函数,因此在使用 private void initInterstitialAdPrepare() { interstitialAd = new InterstitialAd(this, "xxxxxxxx_xxxxxxxxx"); interstitialAd.setAdListener(new InterstitialAdListener() { @Override public void onInterstitialDisplayed(Ad ad) { // Interstitial ad displayed callback Log.e(TAG, "Interstitial ad displayed."); } @Override public void onError(Ad ad, AdError adError) { // Ad error callback Log.e(TAG, "Interstitial ad failed to load: " + adError.getErrorMessage()); } @Override public void onAdLoaded(Ad ad) { // Interstitial ad is loaded and ready to be displayed Log.d(TAG, "Interstitial ad is loaded and ready to be displayed!"); } // Show the ad interstitialAd.show(); } 时可以将其读取为字符串,但是该函数有多行,因此我不知道如何编写。

这就是我想写的

compile()

我想要一种只用一行编写函数的方法(或仍然使用def function(): string = "string" print(string) new_func = "def function(): string = 'strung' # I don't know how to include the other line here " new_code = compile(new_func,"",'exec') eval(new_code) function() eval()来格式化该函数的任何其他方法

2 个答案:

答案 0 :(得分:2)

好像您想使用多行字符串。请在字符串的开头和结尾处使用三引号:

def function():
    string = "string"
    print(string)

new_func = """
def do_stuff():
    string = 'strung' #one line
    print(string) #two lines

"""


new_code = compile(new_func,"",'exec')

eval(new_code)

function()
do_stuff()

有关其他样式的多行字符串,请参见以下答案:Pythonic way to create a long multi-line string

玩得开心。

答案 1 :(得分:1)

您可以按照安德鲁(Andrew)的建议使用python多行。如果相反,您想要的是单行,那么请记住在函数字符串中使用blogger_service = service.GDataService('user@example.com', 'secretPassword') blogger_service.source = 'exampleCo-exampleApp-1.0' blogger_service.service = 'blogger' blogger_service.account_type = 'GOOGLE' blogger_service.server = 'www.blogger.com' blogger_service.ProgrammaticLogin() blogger_service.source,以免造成缩进。例如:

\n