I'm a newbie in Python. I'm trying to apply some dynamics function ( startswith()
, replace()
, exec..) defined as string.
I've this code:
access_number = 'CF-12345'
condition = 'str({v}).startswith("CF-", 0)'
result = {}
exec (condition.format(v = access_number)) in r
but I've this error:
Traceback (most recent call last):
File "/home/main.py", line 11, in <module>
exec (condition.format(v = access_number)) in r
File "<string>", line 1, in <module>
NameError: name 'CF' is not defined
I don't know what I'm doing wrong.
Any help would be appreciated.
Try using print statements as your diagnostic, if you run
access_number = 'CF-12345'
condition = 'str({v}).startswith("CF-", 0)'
result = {}
print condition
print condition.format(v=access_number)
exec (condition.format(v = access_number)) in result
the output is
str({v}).startswith("CF-", 0)
str(CF-12345).startswith("CF-", 0)
Traceback (most recent call last):
File "stuff.py", line 8, in <module>
exec (condition.format(v = access_number)) in result
File "<string>", line 1, in <module>
NameError: name 'CF' is not defined
Notice the second line has str(CF-1234)
this is trying to subtract 1234 from the variable CF.
try
access_number = '"CF-12345"'
condition = 'str({v}).startswith("CF-", 0)'
result = {}
exec (condition.format(v = access_number)) in result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.