| | |
Extracting the literal name of a variable, not the contents?
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
•
•
Join Date: Oct 2009
Posts: 4
Reputation:
Solved Threads: 0
Hi, I have a problem. I basically have this python code, that generates a file.
I'm trying to get it to output a html file with a chosen name (chosencategory) but the problem is the chosencategory variables are already defined so it attempts to name the html file the contents of the variable.
What i'm basically trying to do is extract the literal name of the variable, and not the contents. Is there any way to do this?
Is there anyway I can do this? btw I'm a programming noob.
example of the variable's output (chosencategory output)
the error i get:
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
build_html(sports)
File "C:/Documents and Settings/Administrator/Desktop/New Folder/popularity3.py", line 26, in build_html
filename = '%s.html' %(chosenCategory)
TypeError: not all arguments converted during string formatting
I understand this error, it's because it's trying to use all the contents of the variable (above) to create the html file. I just want the file to be called sports.html
Thanks for the help guys
I'm trying to get it to output a html file with a chosen name (chosencategory) but the problem is the chosencategory variables are already defined so it attempts to name the html file the contents of the variable.
What i'm basically trying to do is extract the literal name of the variable, and not the contents. Is there any way to do this?
Is there anyway I can do this? btw I'm a programming noob.
Python Syntax (Toggle Plain Text)
output_file = file(filename, 'w') def build_html(chosenCategory): #my attempt, which returned an error filename = '%s.html' %(chosenCategory) print chosenCategory
example of the variable's output (chosencategory output)
Python Syntax (Toggle Plain Text)
>>> print sports (('AFL', 6L), ('American Football', 2L), ('Backgammon', 1L), ('Badminton', 2L), ('Baseball', 2L), ('Basketball', 10L), ('Bowling', 1L), ('Chess', 1L), ('Climbing', 1L), ('Cricket', 11L), ('Cross Country', 1L), ('Cycling', 2L), ('Dancing', 1L), ('Darts', 1L), ('Dodgeball', 1L), ('Dog Racing', 1L), ('Dog Sledding', 1L), ('Drifting', 1L), ('Extreme Ironing', 1L), ('Fencing', 1L), ('Fishing', 1L), ('Frisbee', 1L), ('Golf', 5L), ('Hacky-Sack', 1L), ('Hockey', 1L), ('Horse Riding', 1L), ('Ice Hockey', 1L), ('Jogging', 1L), ('Karate', 3L), ('MMA', 1L), ('Modern Pentahlon', 1L), ('Moto GP', 1L), ('Motocross', 2L), ('Mountain Climbing', 1L), ('Netball', 1L), ('Pool', 1L), ('Racing', 1L), ('Rugby League', 15L), ('Rugby Union', 6L), ('Running', 2L), ('Skateboarding', 2L), ('Skiing', 2L), ('Snooker', 1L), ('Snowboarding', 2L), ('Soccer', 27L), ('Softball', 1L), ('Surfing', 1L), ('Swimming', 4L), ('Table Tennis', 3L), ('Tennis', 13L), ('Touch Football', 1L), ('Track and Field', 1L), ('Trekking', 1L), ('Volleyball', 5L), ('Water Polo', 1L), ('White Water Rafting', 1L), ('Wii Sports', 1L), ('World Superbikes', 1L))
the error i get:
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
build_html(sports)
File "C:/Documents and Settings/Administrator/Desktop/New Folder/popularity3.py", line 26, in build_html
filename = '%s.html' %(chosenCategory)
TypeError: not all arguments converted during string formatting
I understand this error, it's because it's trying to use all the contents of the variable (above) to create the html file. I just want the file to be called sports.html
Thanks for the help guys Last edited by qadsia; Oct 13th, 2009 at 9:20 am.
•
•
Join Date: Oct 2009
Posts: 4
Reputation:
Solved Threads: 0
0
#3 Oct 13th, 2009
Thank you so much for the suggestion, but the problem is it needs to be called as a variable because it's variable properties are used in another part of the program.
Is there a way to extract it as a string in the
define function area?
or maybe something involving a dictionary?
The annoying bit is i actually completed the program, I just can't get it to output the files with the correct name.
ok to be more clear, I want the variable sports to still print the data in the sports variable, but I need to also use the name 'sports' as a string to name the html file I create. The problem is I can't just hardcode it in, because there are 6 different categories.
Is there a way to extract it as a string in the
define function area?
or maybe something involving a dictionary?
The annoying bit is i actually completed the program, I just can't get it to output the files with the correct name.
ok to be more clear, I want the variable sports to still print the data in the sports variable, but I need to also use the name 'sports' as a string to name the html file I create. The problem is I can't just hardcode it in, because there are 6 different categories.
Last edited by qadsia; Oct 13th, 2009 at 10:35 am.
1
#4 Oct 13th, 2009
You can not do it in the function you are calling, because the variable is now chosenCategory and the function does not have the information that this variable used to be called sports or whatever.
So my suggestion is to make the category string the first item in the tuple and then use a slice of the tuple for normal use ...
So my suggestion is to make the category string the first item in the tuple and then use a slice of the tuple for normal use ...
python Syntax (Toggle Plain Text)
def build_html(chosenCategory): filename = '%s.html' % (chosenCategory[0]) return filename # test # make the category string the first item in the tuple sports = ('sports', ('AFL', 6L), ('American Football', 2L)) fname = build_html(sports) print fname # sports.html # to use the tuple for its values slice out the category name print sports[1:] # (('AFL', 6L), ('American Football', 2L))
Last edited by vegaseat; Oct 13th, 2009 at 12:31 pm. Reason: slice
May 'the Google' be with you!
2
#5 Oct 13th, 2009
This is a very hacked solution but:
You could even be brazen and shorten that for loop to a single list comprehension (albeit a very long one):
python Syntax (Toggle Plain Text)
>>> sports = ## Defined as above - snipped for length >>> def build_html(chosenCategory): ... up_locals = sys._getframe(1).f_locals ... for each_var in up_locals: ... if id(up_locals[each_var]) == id(chosenCategory): ... var_name = each_var ... filename = '%s.html' % (var_name) ... print filename ... >>> build_html(sports) sports.html >>>
python Syntax (Toggle Plain Text)
def build_html(chosenCategory): var_name = [each_var for each_var in sys._getframe(1).f_locals if id(sys._getframe(1).f_locals[each_var]) == id(chosenCategory)][0] filename = '%s.html' % (var_name) print filename
•
•
Join Date: Oct 2009
Posts: 4
Reputation:
Solved Threads: 0
0
#6 Oct 14th, 2009
Thank you , both suggestions worked perfectly
The program was running perfectly!
My problem now is I realised I actually needed a string input. e.g. ('sports') So now I need the complete opposite.
Is there a way to use a string to call a previously named variable? Thank you so much
i've been researching and something like exec or .append or vars() might be what i'm looking for.. what do you think??
The program was running perfectly!My problem now is I realised I actually needed a string input. e.g. ('sports') So now I need the complete opposite.
Is there a way to use a string to call a previously named variable? Thank you so much
i've been researching and something like exec or .append or vars() might be what i'm looking for.. what do you think??
2
#7 Oct 14th, 2009
•
•
•
•
Is there a way to use a string to call a previously named variable?
python Syntax (Toggle Plain Text)
>>> sports = [1,23,4] >>> eval( 'sports' ) [1, 23, 4] >>>
•
•
Join Date: Oct 2009
Posts: 4
Reputation:
Solved Threads: 0
0
#8 Oct 14th, 2009
Thanks, the eval function actually worked. But I actually solved the problem like an hour ago, by rewriting my program using a dictionary.
To help anyone else that might be stuck on this in the future,
what I did was use a dictionary with all the variables, which is more powerful than variable apparently? So it allowed me to take a string from the user input and output the data.
But yeah, eval also works, which I had seen it sooner lol. Will use it next time. But yeah, thank you Vegaseat and Jlm699, I appreciate the help so much.
To help anyone else that might be stuck on this in the future,
what I did was use a dictionary with all the variables, which is more powerful than variable apparently? So it allowed me to take a string from the user input and output the data.
But yeah, eval also works, which I had seen it sooner lol. Will use it next time. But yeah, thank you Vegaseat and Jlm699, I appreciate the help so much.
![]() |
Similar Threads
- writing variable contents to a specific line in a file (Shell Scripting)
- Windows XP Installation Error: No Disk Drive? (Windows NT / 2000 / XP)
- getting a variable name (Python)
- How to check a variable's content? (PHP)
- Deitel's "C++ How To Program" exercise 2.18 (C++)
- Will somebody please explain value parameters to me!!! (C)
- Sorting arrays of pointers with function? (C)
- Some help understanding #define with C (C)
Other Threads in the Python Forum
- Previous Thread: Why does this return an error: Lists
- Next Thread: Sieve Program
| Thread Tools | Search this Thread |
accessdenied advanced aliased argv beginner bits calling casino change command convert count csv cturtle cursor def dictionary digital dynamic dynamically enter event examples external file float format frange function google gui hints homework i/o iframe import info input jaunty java keyboard lapse line linux list lists loop microphone mouse multiple newb number numbers obexftp output parameters parsing path port prime programming projects py py2exe pygame pygtk pyopengl python random recursion return scrolledtext signal skinning sprite stderr string strings subprocess table tennis terminal text thread threading time tkinter tlapse tuple tutorial ubuntu unicode urllib urllib2 variable voip web-scrape whileloop windows wxpython






