【问题标题】:Python: Custom print function that prints function textPython:打印函数文本的自定义打印函数
【发布时间】:2020-01-27 23:19:35
【问题描述】:

Python 脚本:

text = "abcde"
print("text[::-1] : ", text[::-1])
print("text[5:0:-1] : ", text[5:0:-1])

输出:

text[::-1] :  edcba
text[5:0:-1] :  edcb

是否可以定义一个自定义函数来避免重复输入? 例如:

text = "abcde"
def fuc(x):
    print(x, ":", x)
    
fuc(text[::-1])
fuc(text[5:0:-1])

要求。输出:

text[::-1] :  edcba
text[5:0:-1] :  edcb

【问题讨论】:

  • 它被称为切片对象。它已经原生存在于 python 中。
  • 我的问题与 silce 对象无关。我想定义一个自定义函数,这样我就不必在 print("b[::-1] : ", b[::-1]) 中键入两次“b[::-1]”。
  • @Sayse - 我收到错误“文件“”,第 1 行 (b[::1]=) ^ SyntaxError: invalid syntax
  • 可以使用 eval,例如 def debug_print(expression): print(expression, ':', eval(expression))。然后你会用字符串调用它,例如debug_print('a[::-1]')。如果它是用于调试目的而不是用于生产代码,这不会很糟糕,但如果 expression 来自不受信任的输入,它肯定会带来安全风险

标签: python printing custom-function f-string


【解决方案1】:

在 python 3.8+ 中,您可以使用self documenting expression

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

【讨论】:

  • 我得到一个 SyntaxError 指向等于:文件“”,第 1 行 (b[::1]=) ^ SyntaxError: invalid syntax
  • @RahulAhuja - 那么看起来你使用的不是 python 3.8
  • 我有 Python 3.7.4 并且正在使用 Jupyter Notebook。
【解决方案2】:

使用 f 字符串可以实现涉及字符串插值的解决方案。但是,f 字符串仅适用于 Python 3.8+

然而,我们可以很容易地实现How to Implement String Interpolation in Python所描述的字符串插值

Current Modification 扩展了上述引用以允许除了变量查找之外的表达式。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    相关资源
    最近更新 更多