Python Forum

Full Version: Custom function that prints function text
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Currently:

a = "abcde"
print("b[::-1] : ", b[::-1])
print("b[5:0:-1] : ", b[5:0:-1])
Output:
Output:
>>> b[::-1] : edcba >>> b[5:0:-1] : edcb
Can a custom function be defined that avoids duplicity in typing?
For ex:

def fuc(a)
    print(a, ":", a) # change here

fuc(b[::-1])
fuc(b[5:0:-1])
Output:
Output:
>>> b[::-1] : edcba >>> b[5:0:-1] : edcb
Yes
Here's a dangerous way - you don't want to expose the eval() function to anything a user might enter for security purposes
def double_print(mystring) :
    print(mystring, eval(mystring))

a = "abcde"
double_print("a[::-1]")
Output:
a[::-1] edcba
Maybe elaborate further what your actual goal is, because what you are doing/asking how to do is let say weird
I just mention that it will not work this way as b is not defined and you will get NameError anyway.

One can use f-strings debugging feature introduced in Python 3.8 for somewhat similar results ('=' instead of ':'):

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