String formatting problems and line number concatenation

I am coming from C # background and I am doing this:

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

Thus, an integer is automatically converted to a string and displayed.

In python, I get an error:

print 'hello' + 10

Do I need to convert to a string every time?

How do I do this in python?

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

I really like python, thanks for your help!

+3
source share
4 answers
>>> "www.someurl.com/{0}/blah.html".format(100)
'www.someurl.com/100/blah.html'

you can skip 0in python 2.7 or 3.1.

+3
source

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 want to support named arguments, you can pass dict.

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

, , :

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

__str__. [*] Python docs. Python 3+, .

, join . .

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

- , (, Python < 2.5), . . , .

[*] Unicode __unicode__.

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

:

print "hello", 10

, , ( ). ​​

+2

To format strings that include different types of values, use% to insert the value in the 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 use% i as stand-in. This varies depending on what type of variable you need to use. % s will be for strings. There is a list here on the python docs site .

+1
source

Source: https://habr.com/ru/post/1757502/


All Articles