Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here
  #1  
Old February 3rd, 2002, 03:39 PM
nkuzma nkuzma is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2002
Posts: 1 nkuzma User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Question In python, how do you put variables in strings?

It should be very simple, but I seem to be missing it. In perl it would look like this:

$name = (whatever name you input)
$age = (again, whatever you input previously)

then you could display it like:

print "Hello $name, you are $age years old."

I know python could do

print "Hello",name,"you are",age,"years old."

But that doesnt cut it, since it always adds spaces.

print "Hello",name,"!"

whould print:

Hello Jack !

Dont ask me why python forces spaces in there.. is there anyway to just call variables within strings like in perl?

Reply With Quote
  #2  
Old February 4th, 2002, 06:31 AM
Taradino Taradino is offline
Python Prophet
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jun 2001
Location: Amersfoort, The Netherlands
Posts: 45 Taradino User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 8
It is very simple: Just use string format characters.

In this example:
print 'Hello %s, you are %s years old.' % (name, age)

You could also use string concatenation like this:
print 'Hello '+name+', you are '+age+' years old.'
But this is slower, and IMO less readable.
__________________
Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems. - Jamie Zawinski, in comp.lang.emacs

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > In python, how do you put variables in strings?


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump


Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 





© 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway