Python Forum
Convert any Python expression to a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert any Python expression to a string
#1
I'd like to be able to convert any Python expressions to a string. Something like this:
def show(a):
    print(stringify(a))

>>> show(5 + 4)
"5 + 4"
In C, the above is pretty easy but it uses pre-processor macros. But to my knowledge, in Python the expressions 5 + 4 is evaluated before the show() function is even called.

However, before giving up, I wanted to ask if there might be some trick with inspect or ast that might work.
Reply
#2
Why on earth would you want to do this? The method depends on where you are getting the expressions and the values you want as a string.

A Python script is a just a text file, just a string, so if you want to find arithmetical expressions in a text file, do this:

import re

# a Python script is just a text file
# if the expressions are statically assigned in a Python script
# use a regex to find arithmetical expressions or anything else

# look for 1 or more numbers, followed by space and or an operator followed by at least 1 number
maths = re.compile(r'([0-9]+)([\s+/*-]+)([0-9]+)')
# how this works example
line = 'e = 5 + 4'
res = maths.search(line)
res.groups() # returns ('5', ' + ', '4')

path2text = '/home/peterr/PVE/quatsch.py'

with open(path2text) as infile:
    text_list = infile.readlines()

for line in text_list:
    res = maths.search(line)
    if res:
        print(line, res.groups())
Gives:

Output:
e = 5 + 4 ('5', ' + ', '4') print(5 + 4) ('5', ' + ', '4') d = '5 + 4' ('5', ' + ', '4')
If you are assigning the variables dynamically:

# print(5 + 4) will print 9
# if you are dynamically assigning the variables, the result of input() is already a string:
arithmetic = input('Enter a number, an operator and another number, separated by a space ... ').split()
print(' '.join(arithmetic))
Output:
5 + 4
If you statically assign individual values:

# if you assign individual values as integers
a = 5
b = 4
# you can't str(+) you will get an error
operator = input('Enter the operator you want to use ... ')
c = str(a) + operator + str(b)
print(c)
Reply
#3
(Jun-16-2025, 02:06 PM)voidtrance Wrote: I'd like to be able to convert any Python expressions to a string. Something like this:
def show(a):
    print(stringify(a))

>>> show(5 + 4)
"5 + 4"

The object a is evaluated, before it's called with the function. There are ways to get the last stackframe, but you won't get the source code of it, if it's not a function.

What you could do is disassemble the source code:
PS C:\Users\xxxx> py -3.13 -m dis .\s.py
  0           RESUME                   0

  1           LOAD_CONST               0 (<code object show at 0x000002943B5CD230, file ".\s.py", line 1>)
              MAKE_FUNCTION
              STORE_NAME               0 (show)

  4           LOAD_NAME                0 (show)
              PUSH_NULL
              LOAD_CONST               1 (9)
              CALL                     1
              POP_TOP
              RETURN_CONST             2 (None)

Disassembly of <code object show at 0x000002943B5CD230, file ".\s.py", line 1>:
  1           RESUME                   0

  2           LOAD_GLOBAL              1 (print + NULL)
              LOAD_GLOBAL              3 (stringify + NULL)
              LOAD_FAST                0 (a)
              CALL                     1
              CALL                     1
              POP_TOP
              RETURN_CONST             0 (None)
ATM, I'm at work and have to use Windows....

On Linux, you just call: python3 -m dis ./s.py
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python beginner that needs an expression added to existing script markham 1 1,956 Sep-04-2023, 05:24 AM
Last Post: Pedroski55
  convert string to float in list jacklee26 6 4,552 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  how to convert tuple value into string mg24 2 5,281 Oct-06-2022, 08:13 AM
Last Post: DeaD_EyE
  Convert string to float problem vasik006 8 6,758 Jun-03-2022, 06:41 PM
Last Post: deanhystad
  Convert a string to a function mikepy 8 7,192 May-13-2022, 07:28 PM
Last Post: mikepy
Question How to convert string to variable? chatguy 5 7,235 Apr-12-2022, 08:31 PM
Last Post: buran
  Convert string to int Frankduc 8 5,023 Feb-13-2022, 04:50 PM
Last Post: menator01
  Convert string to path using Python 2.7 tester_V 10 11,413 Nov-20-2021, 02:20 PM
Last Post: snippsat
  printing an string instead of a expression Underscore 2 3,134 Oct-11-2021, 03:10 PM
Last Post: deanhystad
  Convert each element of a list to a string for processing tester_V 6 9,004 Jun-16-2021, 02:11 AM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020