Re: Is there an easier way without having to call the str() method?
|
Yash Patel |
|
3/25/2008 12:24:05 AM |
Hi Shirly, Um, what language are you working in? Post Comments |
|
Python. So here is some code...
num = raw_input("Pick a number: ") num = int(num) print "Your number times 5 is", num * 5, "."
This produces a space between num and the period. If I try to use "+" I get an error trying to concatenate a str and int. It's possible to print str(num) and then concatenate that result with the period to eliminate the space. But I was wondering if there was a more obvious way than calling the str() function.
Post Comments |
|
Re: So why not use the str() conversion?
|
Sardha Henry |
|
3/25/2008 12:33:28 AM |
So why not use the str() conversion? It's probably just as easy...
Code: ( python ) -
num = int(raw_input("Pick a number: ")) -
print "Your number times 5 is " + str(num * 5) + "."
I guess it's a matter of preference, but that's h ow I do all my string/int concatenations... Post Comments |
|
Re: Is there an easier way without having to call the str() method?
|
Poicramuikri Cevilto |
|
3/25/2008 12:28:03 AM |
Moved the thread to the Python forum Post Comments |
|
Thanks! Sorry about that. Post Comments |
|
Re: Is there an easier way without having to call the str() method?
|
Dan D'Souza |
|
3/25/2008 12:31:55 AM |
And don't forget Code tags.
My favorite way (because there are several) is using string formatting. Code: ( text ) - >>>
num = raw_input("Pick a number: ") - >>>
num = int(num) - >>>
print "Your number times 5 is %d."%(num * 5) - Your number times 5 is 30.
You could also move the int() call to tighten the code a little. Code: ( text ) - >>>
num = int(raw_input("Pick a number: ")) - >>>
print "Your number times 5 is %d."%(num * 5) - Your number times 5 is 40.
or for that matter Code: ( text ) - print "Your number times 5 is %d."%(int(raw_input("Pick a number: ")) * 5)
Onc e you start worrying about what happens if the user enters a non numeric value like "a&quo t; you will want to explore the try: and except: block. Post Comments |
|
Re: Is there an easier way without having to call the str() method?
|
Mocco Tokkendo |
|
3/25/2008 12:35:06 AM |
I try to avoid string concatenation where possible. String formating with %s uses str() to generate the string. Code: ( python ) - num = int(raw_input("Pick a number: "))
- print "Your number times 5 is %s." % (num * 5)
Post Comments |
|
Thanks to you all for responding. That was very helpful and educational!
< /p> Post Comments |
|