0

Python script:

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

Output:

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

Can a custom function be defined that avoids duplicity in typing? For ex:

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

Reqd. Output:

text[::-1] :  edcba
text[5:0:-1] :  edcb
  • It's called a slice object. It already exists natively in python. – Error - Syntactical Remorse Jan 27 '20 at 23:22
  • My question is not related to silce object. I want to define a custom function that would save me the trouble of having to type "b[::-1]" twice in print("b[::-1] : ", b[::-1]). –  Jan 27 '20 at 23:24
  • @Sayse - I got an error "File "", line 1 (b[::1]=) ^ SyntaxError: invalid syntax –  Jan 27 '20 at 23:28
  • you *could* use eval, something like `def debug_print(expression): print(expression, ':', eval(expression))`. and then you would call it with the string, e.g. `debug_print('a[::-1]')`. This wouldn't be terrible if it is for debugging purposes and not for production code, but it definitely presents a security risk if `expression` is from an untrusted input – juanpa.arrivillaga Jan 28 '20 at 00:22

2 Answers2

2

In python 3.8+, you can use a self documenting expression

>>> print(f"{a[::-1]=}") 
a[::-1]='edcba'
Sayse
  • 42,633
  • 14
  • 77
  • 146
0

A solution involving string interpolation is possible using f-strings. However, f-strings are only available with Python 3.8+

However, we can easily implement string interpolation as described by How to Implement String Interpolation in Python

Current Modification extends the above reference to allow expressions in addition to variable lookups.

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
DarrylG
  • 16,732
  • 2
  • 17
  • 23