第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Python:打印函數(shù)文本的自定義打印函數(shù)

Python:打印函數(shù)文本的自定義打印函數(shù)

眼眸繁星 2022-07-12 10:09:17
Python腳本:text = "abcde"print("text[::-1] : ", text[::-1])print("text[5:0:-1] : ", text[5:0:-1])輸出:text[::-1] :  edcbatext[5:0:-1] :  edcb可以定義一個(gè)自定義函數(shù)來(lái)避免輸入重復(fù)嗎?例如:text = "abcde"def fuc(x):    print(x, ":", x)    fuc(text[::-1])fuc(text[5:0:-1])要求。輸出:text[::-1] :  edcbatext[5:0:-1] :  edcb
查看完整描述

2 回答

?
慕雪6442864

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊

在 python 3.8+ 中,您可以使用自記錄表達(dá)式


>>> print(f"{a[::-1]=}") 

a[::-1]='edcba'


查看完整回答
反對(duì) 回復(fù) 2022-07-12
?
慕哥6287543

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊

使用 f 字符串可以實(shí)現(xiàn)涉及字符串插值的解決方案。但是,f 字符串僅適用于 Python 3.8+


但是,我們可以很容易地實(shí)現(xiàn)字符串插值,如如何在 Python 中實(shí)現(xiàn)字符串插值


Current Modification 擴(kuò)展了上述參考,以允許除了變量查找之外的表達(dá)式。


import sys

from re import sub


def interp(s):

  '''Implement simple string interpolation to handle

    "{var}" replaces var with its value from locals

    "{var=}" replaces var= with var=value, where value is the value of var from locals

    "{expressions} use eval to evaluate expressions (make eval safe by only allowing items from local functions and variables in expression'''


  # 1. Implement self-documenting expressions similar to https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging

  s1 = sub( r'{\s*(.*?)=\s*}', lambda m: m.group(1) + '=' + '{' + m.group(1) + '}', s)


  # Get the locals from the previous frame

  previous_frame = sys._getframe(1)  # i.e. current frame(0), previous is frame(1)

  d = previous_frame.f_locals        # get locals from previous frame


  # 2--Replace variable and expression with values

  # Use technique from http://lybniz2.sourceforge.net/safeeval.html to limit eval to make it safe

  # by only allowing locals from d and no globals

  s2 = sub(r'{\s*([^\s]+)\s*}', lambda m: str(d[m.group(1)]) if m.group(1) in d else str(eval(m.group(1), {}, d)), s1)

  return s2


# Test

a = "abcde"


print(interp("a has value {a}"))  # without self-doc =

#Output>>> a has value abcde


print(interp("{a[::-1]=}"))       # with self-doc =

#Output>>> a[::-1]=edcba


print(interp('{a[4:0:-1]=}'))     # with self-doc =

#Output>>> a[4:0:-1]=edcb


print(interp('sum {1+1}') # without self-doc =

#Output>>> sum 2


print(interp('{1+1=}'))  # with self-doc =

#Output>>> 1+1=2



查看完整回答
反對(duì) 回復(fù) 2022-07-12
  • 2 回答
  • 0 關(guān)注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)