简体   繁体   中英

Adding text to the front - Python

I have the below code

Test1 =  Price[Product.index(TestABC)]+   AddQTYPriceA

print Test1
print "try this test" + Test1

When it needs to print Test 1 it gives the correct answer. I want to try and add text to the front of it and so I have entered print "try this test" + Test1

For the second print command it gives the following error.

Traceback (most recent call last):
  File "C:\Python26\data.py", line 78, in <module>
    print "try this test" + Test1
TypeError: cannot concatenate 'str' and 'float' objects

Can someone assist how I can get text to appear at the front.

Greggy D

In order to concatenate the string and float you need to cast the float as a string using the str() function.

print "try this test " + str(Test1)

Or you could use the .format() string method:

print "try this test {0}".format(Test1)

Both of these methods are documented on the python string built-in type page .

try this :

print "try this test", Test1

# let's assume that Test1 is equal to 2.5, you will get : 
>>> try this test 2.5

no need to concatenate the strings, let python do the job ;)

EDIT : As mentionned by Lattyware, python will automatically add a space between the 2 parts of the resulting string.

Ok, got my wrist slapped for using the traditional approach.

Use the string.format approach as it's very flexible:

print "try this test {0}".format(Test1)

str.format() takes an arbitrary number of arguments, and maps sequentially to the {slot} given in the string. So you can do:

"{0} {1} {2}".format("test", 1, 0.01) # => "test 1 0.01"

Nice and simple!

So only do the following if no one is looking:

print "try this test %f" % (Test1)

You can try this example:

print "try this test %s" % str(Test1)

which allows you to put text at the beginning or somewhere else in relation to Test1.

You have to convert the output of the Test1 to the same data - print can handle any data type but the + operator only handles the same type.

Options are:

  • cast whatever output Test1 gives to string using str()

  • define a method to handle adding of Test1 to other things to return string.

  • make it the Test1 class actually generate the whole string output so there would be no need to concatenate it, you can implement __str__() method

  • use many of the options to format the output

But I believe that the main point to take home is that the + is not overloaded in python as it is in other languages and one needs to explicitly cast different types.

Example what needs to be added to your Price class to be able to use your print code unmodified:

class Price(object):
    def __add__(self, x):
        return '%s %s' % (self, x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM