Blankman
Blankman

Reputation: 266978

String formatting issues and concatenating a string with a number

I'm coming from a c# background, and I do this:

Console.Write("some text" + integerValue);

So the integer automatically gets converted to a string and it outputs.

In python I get an error when I do:

print 'hello' + 10

Do I have to convert to string everytime?

How would I do this in python?

String.Format("www.someurl.com/{0}/blah.html", 100);

I'm beginning to really like python, thanks for all your help!

Upvotes: 3

Views: 2075

Answers (4)

Tim McNamara
Tim McNamara

Reputation: 18375

From Python 2.6:

>>> "www.someurl.com/{0}/blah.html".format(100)
'www.someurl.com/100/blah.html'

To support older environments, the % operator has a similar role:

>>> "www.someurl.com/%d/blah.html" % 100
'www.someurl.com/100/blah.html'

If you would like to support named arguments, then you can can pass a dict.

>>> url_args = {'num' : 100 }
>>> "www.someurl.com/%(num)d/blah.html" % url_args
'www.someurl.com/100/blah.html'

In general, when types need to be mixed, I recommend string formatting:

>>> '%d: %s' % (1, 'string formatting',)
'1:  string formatting'

String formatting coerces objects into strings by using their __str__ methods.[*] There is much more detailed documentation available on Python string formatting in the docs. This behaviour is different in Python 3+, as all strings are unicode.

If you have a list or tuple of strings, the join method is quite convenient. It applies a separator between all elements of the iterable.

>>> ' '.join(['2:', 'list', 'of', 'strings'])
'2: list of strings'

If you are ever in an environment where you need to support a legacy environment, (e.g. Python <2.5), you should generally avoid string concatenation. See the article referenced in the comments.

[*] Unicode strings use the __unicode__ method.

>>> u'3: %s' % ':)'
u'3: :)'

Upvotes: 4

xnine
xnine

Reputation: 100

For string formatting that includes different types of values, use the % to insert the value into a string:

>>> intvalu = 10
>>> print "hello %i"%intvalu
hello 10
>>> 

so in your example:

>>>print "www.someurl.com/%i/blah.html"%100
www.someurl.com/100/blah.html

In this example I'm using %i as the stand-in. This changes depending on what variable type you need to use. %s would be for strings. There is a list here on the python docs website.

Upvotes: 1

user395760
user395760

Reputation:

Additionally to string formatting, you can always print like this:

print "hello", 10

Works since those are separate arguments and print converts non-string arguments to strings (and inserts a space in between).

Upvotes: 2

SilentGhost
SilentGhost

Reputation: 319561

>>> "www.someurl.com/{0}/blah.html".format(100)
'www.someurl.com/100/blah.html'

you can skip 0 in python 2.7 or 3.1.

Upvotes: 3

Related Questions