Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Appending a digit to a string

Status
Not open for further replies.

Winstonb

Technical User
Aug 11, 2001
29
GB
Hello,

New to Python / jython.
Have a problem appending a digit on to the end of a string as per below. Does anyone know a way around this ?

contents of config.py file....
total = 2
var1 = one
var2 = two

contents script.py file.....
import config
count = 1
while count <= import.total:
# What I want to do now is firstly print the
# resultant of config.var1 (one),
# and then config.var2 (two) on the 2nd loop.
# ie, using something along the lines of
# print "config.var" + count.
count = count + 1

Thanks
Winston
 
Hi, Winston,

You could use a formatted print statement like this:

Code:
print "config.var%d" % count


 
I like to concat non-string by using the ` character (not sure the name... I call it accent grave... is left of the number 1 on my keyboard with the tilde ~)

print "config.var" + `count`

Nancy
 
Thanks to both of you for the help, much appreciated.
What I'm looking for however is something that will print one and then two, not literally config.var1 and config.var2.

Thanks again
Winston
 
You're looking for the [tt]eval[/tt] function. It takes a string argument and evaluates it as Python code. So you can construct the name of your variable as a string, and then [tt]eval[/tt] it to get its value.
Code:
for i in range(1,3):
     print eval('var' + `i`)


eclecticNancy, in Unix parlance, we usually call the ` character a backtick or backquote. The Python documentation seems to prefer calling it a reverse quote.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top