【发布时间】: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