How can I concatenate str and int objects?Python: TypeError: cannot concatenate 'str' and 'int' objectsHow can I concatenate a string and a number in Python?Making a string out of a string and an integer in PythonPython TypeError must be str not intUnsupported operand type(s) for +: 'int' and 'str'Can I use a variable inside of an input statement?Python concatenation of string and integer sumTypeError: can only concatenate str (not “int”) to str - (New Learner)TypeError: can only concatenate str (not “int”) to strUnable to concatenate integer in my “print” statementHow can I concatenate two arrays in Java?How do I check whether a file exists without exceptions?How can I safely create a nested directory?“Least Astonishment” and the Mutable Default ArgumentHow to replace all occurrences of a string in JavaScriptProper way to declare custom exceptions in modern Python?How do I concatenate two lists in Python?How to check whether a string contains a substring in JavaScript?How do I convert a String to an int in Java?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

What is this little owl-like bird?

Why different specifications for telescopes and binoculars?

Is this a reference to the film Alien in the novel 2010 Odyssey Two?

How do native German speakers usually express skepticism (using even) about a premise?

When an electron changes its spin, or any other intrinsic property, is it still the same electron?

How do you move up one folder in Finder?

Elf (adjective) vs. Elvish vs. Elven

Why does wrapping Aluminium foil around my food help it keep warm, aluminium be good conductor should have no effect?

Can Jimmy hang on his rope?

[Future]Historical experience as a guide to warship design?

GDPR rights when subject dies; does family inherit subject rights?

Can I play a mimic PC?

What is /bin/red

What is the minimum time required for final wash in film development?

How can a dictatorship government be beneficial to a dictator in a post-scarcity society?

The three greedy pirates

Yet another hash table in C

How do we handle pauses in a dialogue?

Backspace functionality in normal mode

The rigidity of the countable product of free groups

Distinguish the explanations of Galadriel's test in LotR

Why did Old English lose both thorn and eth?

How effective would wooden scale armor be in a medieval setting?

What attributes and how big would a sea creature(s) need to be able to tow a ship?



How can I concatenate str and int objects?


Python: TypeError: cannot concatenate 'str' and 'int' objectsHow can I concatenate a string and a number in Python?Making a string out of a string and an integer in PythonPython TypeError must be str not intUnsupported operand type(s) for +: 'int' and 'str'Can I use a variable inside of an input statement?Python concatenation of string and integer sumTypeError: can only concatenate str (not “int”) to str - (New Learner)TypeError: can only concatenate str (not “int”) to strUnable to concatenate integer in my “print” statementHow can I concatenate two arrays in Java?How do I check whether a file exists without exceptions?How can I safely create a nested directory?“Least Astonishment” and the Mutable Default ArgumentHow to replace all occurrences of a string in JavaScriptProper way to declare custom exceptions in modern Python?How do I concatenate two lists in Python?How to check whether a string contains a substring in JavaScript?How do I convert a String to an int in Java?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








58















If I try to do the following:



things = 5
print("You have " + things + " things.")


I get the following error in Python 3.x:



Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int


... and a similar error in Python 2.x:



Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects


How can I get around this problem?










share|improve this question






























    58















    If I try to do the following:



    things = 5
    print("You have " + things + " things.")


    I get the following error in Python 3.x:



    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: must be str, not int


    ... and a similar error in Python 2.x:



    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: cannot concatenate 'str' and 'int' objects


    How can I get around this problem?










    share|improve this question


























      58












      58








      58


      14






      If I try to do the following:



      things = 5
      print("You have " + things + " things.")


      I get the following error in Python 3.x:



      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      TypeError: must be str, not int


      ... and a similar error in Python 2.x:



      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      TypeError: cannot concatenate 'str' and 'int' objects


      How can I get around this problem?










      share|improve this question
















      If I try to do the following:



      things = 5
      print("You have " + things + " things.")


      I get the following error in Python 3.x:



      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      TypeError: must be str, not int


      ... and a similar error in Python 2.x:



      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      TypeError: cannot concatenate 'str' and 'int' objects


      How can I get around this problem?







      python string python-3.x concatenation python-2.x






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 9 '17 at 2:11







      Zero Piraeus

















      asked Sep 4 '14 at 22:28









      Zero PiraeusZero Piraeus

      32.4k18 gold badges109 silver badges131 bronze badges




      32.4k18 gold badges109 silver badges131 bronze badges






















          4 Answers
          4






          active

          oldest

          votes


















          84





          +250









          The problem here is that the + operator has (at least) two different meanings in Python: for numeric types, it means "add the numbers together":



          >>> 1 + 2
          3
          >>> 3.4 + 5.6
          9.0


          ... and for sequence types, it means "concatenate the sequences":



          >>> [1, 2, 3] + [4, 5, 6]
          [1, 2, 3, 4, 5, 6]
          >>> 'abc' + 'def'
          'abcdef'


          As a rule, Python doesn't implicitly convert objects from one type to another1 in order to make operations "make sense", because that would be confusing: for instance, you might think that '3' + 5 should mean '35', but someone else might think it should mean 8 or even '8'.



          Similarly, Python won't let you concatenate two different types of sequence:



          >>> [7, 8, 9] + 'ghi'
          Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          TypeError: can only concatenate list (not "str") to list


          Because of this, you need to do the conversion explicitly, whether what you want is concatenation or addition:



          >>> 'Total: ' + str(123)
          'Total: 123'
          >>> int('456') + 789
          1245


          However, there is a better way. Depending on which version of Python you use, there are three different kinds of string formatting available2, which not only allow you to avoid multiple + operations:



          >>> things = 5




          >>> 'You have %d things.' % things # % interpolation
          'You have 5 things.'




          >>> 'You have things.'.format(things) # str.format()
          'You have 5 things.'




          >>> f'You have things things.' # f-string (since Python 3.6)
          'You have 5 things.'


          ... but also allow you to control how values are displayed:



          >>> value = 5
          >>> sq_root = value ** 0.5
          >>> sq_root
          2.23606797749979




          >>> 'The square root of %d is %.2f (roughly).' % (value, sq_root)
          'The square root of 5 is 2.24 (roughly).'




          >>> 'The square root of v is sr:.2f (roughly).'.format(v=value, sr=sq_root)
          'The square root of 5 is 2.24 (roughly).'




          >>> f'The square root of value is sq_root:.2f (roughly).'
          'The square root of 5 is 2.24 (roughly).'


          Whether you use % interpolation, str.format(), or f-strings is up to you: % interpolation has been around the longest (and is familiar to people with a background in C), str.format() is often more powerful, and f-strings are more powerful still (but available only in Python 3.6 and later).



          Another alternative is to use the fact that if you give print multiple positional arguments, it will join their string representations together using the sep keyword argument (which defaults to ' '):



          >>> things = 5
          >>> print('you have', things, 'things.')
          you have 5 things.
          >>> print('you have', things, 'things.', sep=' ... ')
          you have ... 5 ... things.


          ... but that's usually not as flexible as using Python's built-in string formatting abilities.




          1 Although it makes an exception for numeric types, where most people would agree on the 'right' thing to do:



          >>> 1 + 2.3
          3.3
          >>> 4.5 + (5.6+7j)
          (10.1+7j)


          2 Actually four ... but template strings are rarely used and somewhat awkward.






          share|improve this answer




















          • 2





            This answer is great in that it provides both background info and multiple solutions, but the actual solutions are buried in the middle of a wall of text. It would benefit from a TLDR at the beginning (as a form of progressive disclosure).

            – Helen
            Dec 29 '16 at 20:10






          • 8





            @Helen this canonical Q/A is consciously written as a bait & switch – the question has a "gimme teh codez" style, while the answer makes a point of not immediately providing a "gimme teh codez" solution. I disagree that the inverted pyramid / progressive disclosure approach is a good one for beginner-level instruction; it improves the apparent productivity of bad programmers (who will indeed "dr" the "tl" remainder) at the expense of those who will later maintain their code. I'd rather help potentially great programmers than definitively awful ones, and try to contribute accordingly to SO.

            – Zero Piraeus
            Dec 29 '16 at 21:22











          • Great answer. I learn something new today.

            – alpeshpandya
            Apr 5 '17 at 19:21


















          6














          TL;DR



          1. either: print("You have " + str(things) + " things.") (the old
            school way)


          2. or: print("You have things.".format(things)) (the new pythonic
            and recommended way)



          A bit more verbal explanation:

          Although there is anything not covered from the excellent @Zero Piraeus answer above, I will try to "minify" it a bit:

          You cannot concatenate a string and a number (of any kind) in python because those objects have different definitions of the plus(+) operator which are not compatible with each other (In the str case + is used for concatenation, in the number case it is used to add two numbers together).
          So in order to solve this "misunderstanding" between objects:



          1. The old school way is to cast the number to string with the
            str(anything) method and then concatenate the result with another
            string.

          2. The more pythonic and recommended way is to use the format method which is very versatile (you don't have to take my word on it, read the documentation and this article)

          Have fun and do read the @Zero Piraeus answer it surely worth your time!






          share|improve this answer




















          • 2





            This answer adds nothing new.

            – Ethan Furman
            Apr 5 '17 at 15:45











          • On the bright side, if you delete your answer now you'll get a badge for it (don't recall the name, but it's for deleting an answer with at least 3 upvotes).

            – Ethan Furman
            Apr 5 '17 at 15:49






          • 3





            @EthanFurman I think you are looking for this :) stackoverflow.com/help/badges/37/disciplined

            – Adam
            Apr 5 '17 at 19:00






          • 1





            @Ethan Furman There is nothing that can really be added to that answer, I just tried to minify it a bit and please the demand for a TL;DR from Helen! The canonical is the Zero Piraeus answer by far!

            – John Moutafis
            Apr 5 '17 at 19:08


















          2














          Python 2.x




          1. 'You have %d things.' % things [1]


          2. 'You have things.'.format(things) [2]

          Python 3.6+




          1. 'You have %d things.' % things [1]


          2. 'You have things.'.format(things) [2]


          3. f'You have things things.' [3]


          Reference



          1. printf-style String Formatting

          2. Built-in types -> str.format

          3. Formatted string literals





          share|improve this answer























          • This adds nothing whatsoever to the existing answer.

            – Zero Piraeus
            Apr 2 '17 at 20:30






          • 3





            @ZeroPiraeus: No it does. Ever heard of 'readability'?

            – ngub05
            Apr 7 '17 at 13:13






          • 1





            And just because someone answered a question before me, it doesn't mean that I can approach it, with my own take (the way I think best describes the answer). If you think that's wrong, I think that'a not more wrong than downvoting someone's answer because you also have an answer for the same question.

            – ngub05
            Apr 7 '17 at 13:16


















          -1














          str.format()



          Another alternative is using str.format() method to concatenate an int into a String.



          In your case:




          Replace




          print("You have " + things + " things.")



          With




          print("You have things".format(things))


          Bonus: for multiple concatenation



          if you have



          first = 'rohit'
          last = 'singh'
          age = '5'
          print("My Username is ".format(first,age,last))





          share|improve this answer























            protected by Jim Fasarakis Hilliard Nov 18 '16 at 20:13



            Thank you for your interest in this question.
            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



            Would you like to answer one of these unanswered questions instead?














            4 Answers
            4






            active

            oldest

            votes








            4 Answers
            4






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            84





            +250









            The problem here is that the + operator has (at least) two different meanings in Python: for numeric types, it means "add the numbers together":



            >>> 1 + 2
            3
            >>> 3.4 + 5.6
            9.0


            ... and for sequence types, it means "concatenate the sequences":



            >>> [1, 2, 3] + [4, 5, 6]
            [1, 2, 3, 4, 5, 6]
            >>> 'abc' + 'def'
            'abcdef'


            As a rule, Python doesn't implicitly convert objects from one type to another1 in order to make operations "make sense", because that would be confusing: for instance, you might think that '3' + 5 should mean '35', but someone else might think it should mean 8 or even '8'.



            Similarly, Python won't let you concatenate two different types of sequence:



            >>> [7, 8, 9] + 'ghi'
            Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
            TypeError: can only concatenate list (not "str") to list


            Because of this, you need to do the conversion explicitly, whether what you want is concatenation or addition:



            >>> 'Total: ' + str(123)
            'Total: 123'
            >>> int('456') + 789
            1245


            However, there is a better way. Depending on which version of Python you use, there are three different kinds of string formatting available2, which not only allow you to avoid multiple + operations:



            >>> things = 5




            >>> 'You have %d things.' % things # % interpolation
            'You have 5 things.'




            >>> 'You have things.'.format(things) # str.format()
            'You have 5 things.'




            >>> f'You have things things.' # f-string (since Python 3.6)
            'You have 5 things.'


            ... but also allow you to control how values are displayed:



            >>> value = 5
            >>> sq_root = value ** 0.5
            >>> sq_root
            2.23606797749979




            >>> 'The square root of %d is %.2f (roughly).' % (value, sq_root)
            'The square root of 5 is 2.24 (roughly).'




            >>> 'The square root of v is sr:.2f (roughly).'.format(v=value, sr=sq_root)
            'The square root of 5 is 2.24 (roughly).'




            >>> f'The square root of value is sq_root:.2f (roughly).'
            'The square root of 5 is 2.24 (roughly).'


            Whether you use % interpolation, str.format(), or f-strings is up to you: % interpolation has been around the longest (and is familiar to people with a background in C), str.format() is often more powerful, and f-strings are more powerful still (but available only in Python 3.6 and later).



            Another alternative is to use the fact that if you give print multiple positional arguments, it will join their string representations together using the sep keyword argument (which defaults to ' '):



            >>> things = 5
            >>> print('you have', things, 'things.')
            you have 5 things.
            >>> print('you have', things, 'things.', sep=' ... ')
            you have ... 5 ... things.


            ... but that's usually not as flexible as using Python's built-in string formatting abilities.




            1 Although it makes an exception for numeric types, where most people would agree on the 'right' thing to do:



            >>> 1 + 2.3
            3.3
            >>> 4.5 + (5.6+7j)
            (10.1+7j)


            2 Actually four ... but template strings are rarely used and somewhat awkward.






            share|improve this answer




















            • 2





              This answer is great in that it provides both background info and multiple solutions, but the actual solutions are buried in the middle of a wall of text. It would benefit from a TLDR at the beginning (as a form of progressive disclosure).

              – Helen
              Dec 29 '16 at 20:10






            • 8





              @Helen this canonical Q/A is consciously written as a bait & switch – the question has a "gimme teh codez" style, while the answer makes a point of not immediately providing a "gimme teh codez" solution. I disagree that the inverted pyramid / progressive disclosure approach is a good one for beginner-level instruction; it improves the apparent productivity of bad programmers (who will indeed "dr" the "tl" remainder) at the expense of those who will later maintain their code. I'd rather help potentially great programmers than definitively awful ones, and try to contribute accordingly to SO.

              – Zero Piraeus
              Dec 29 '16 at 21:22











            • Great answer. I learn something new today.

              – alpeshpandya
              Apr 5 '17 at 19:21















            84





            +250









            The problem here is that the + operator has (at least) two different meanings in Python: for numeric types, it means "add the numbers together":



            >>> 1 + 2
            3
            >>> 3.4 + 5.6
            9.0


            ... and for sequence types, it means "concatenate the sequences":



            >>> [1, 2, 3] + [4, 5, 6]
            [1, 2, 3, 4, 5, 6]
            >>> 'abc' + 'def'
            'abcdef'


            As a rule, Python doesn't implicitly convert objects from one type to another1 in order to make operations "make sense", because that would be confusing: for instance, you might think that '3' + 5 should mean '35', but someone else might think it should mean 8 or even '8'.



            Similarly, Python won't let you concatenate two different types of sequence:



            >>> [7, 8, 9] + 'ghi'
            Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
            TypeError: can only concatenate list (not "str") to list


            Because of this, you need to do the conversion explicitly, whether what you want is concatenation or addition:



            >>> 'Total: ' + str(123)
            'Total: 123'
            >>> int('456') + 789
            1245


            However, there is a better way. Depending on which version of Python you use, there are three different kinds of string formatting available2, which not only allow you to avoid multiple + operations:



            >>> things = 5




            >>> 'You have %d things.' % things # % interpolation
            'You have 5 things.'




            >>> 'You have things.'.format(things) # str.format()
            'You have 5 things.'




            >>> f'You have things things.' # f-string (since Python 3.6)
            'You have 5 things.'


            ... but also allow you to control how values are displayed:



            >>> value = 5
            >>> sq_root = value ** 0.5
            >>> sq_root
            2.23606797749979




            >>> 'The square root of %d is %.2f (roughly).' % (value, sq_root)
            'The square root of 5 is 2.24 (roughly).'




            >>> 'The square root of v is sr:.2f (roughly).'.format(v=value, sr=sq_root)
            'The square root of 5 is 2.24 (roughly).'




            >>> f'The square root of value is sq_root:.2f (roughly).'
            'The square root of 5 is 2.24 (roughly).'


            Whether you use % interpolation, str.format(), or f-strings is up to you: % interpolation has been around the longest (and is familiar to people with a background in C), str.format() is often more powerful, and f-strings are more powerful still (but available only in Python 3.6 and later).



            Another alternative is to use the fact that if you give print multiple positional arguments, it will join their string representations together using the sep keyword argument (which defaults to ' '):



            >>> things = 5
            >>> print('you have', things, 'things.')
            you have 5 things.
            >>> print('you have', things, 'things.', sep=' ... ')
            you have ... 5 ... things.


            ... but that's usually not as flexible as using Python's built-in string formatting abilities.




            1 Although it makes an exception for numeric types, where most people would agree on the 'right' thing to do:



            >>> 1 + 2.3
            3.3
            >>> 4.5 + (5.6+7j)
            (10.1+7j)


            2 Actually four ... but template strings are rarely used and somewhat awkward.






            share|improve this answer




















            • 2





              This answer is great in that it provides both background info and multiple solutions, but the actual solutions are buried in the middle of a wall of text. It would benefit from a TLDR at the beginning (as a form of progressive disclosure).

              – Helen
              Dec 29 '16 at 20:10






            • 8





              @Helen this canonical Q/A is consciously written as a bait & switch – the question has a "gimme teh codez" style, while the answer makes a point of not immediately providing a "gimme teh codez" solution. I disagree that the inverted pyramid / progressive disclosure approach is a good one for beginner-level instruction; it improves the apparent productivity of bad programmers (who will indeed "dr" the "tl" remainder) at the expense of those who will later maintain their code. I'd rather help potentially great programmers than definitively awful ones, and try to contribute accordingly to SO.

              – Zero Piraeus
              Dec 29 '16 at 21:22











            • Great answer. I learn something new today.

              – alpeshpandya
              Apr 5 '17 at 19:21













            84





            +250







            84





            +250



            84




            +250





            The problem here is that the + operator has (at least) two different meanings in Python: for numeric types, it means "add the numbers together":



            >>> 1 + 2
            3
            >>> 3.4 + 5.6
            9.0


            ... and for sequence types, it means "concatenate the sequences":



            >>> [1, 2, 3] + [4, 5, 6]
            [1, 2, 3, 4, 5, 6]
            >>> 'abc' + 'def'
            'abcdef'


            As a rule, Python doesn't implicitly convert objects from one type to another1 in order to make operations "make sense", because that would be confusing: for instance, you might think that '3' + 5 should mean '35', but someone else might think it should mean 8 or even '8'.



            Similarly, Python won't let you concatenate two different types of sequence:



            >>> [7, 8, 9] + 'ghi'
            Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
            TypeError: can only concatenate list (not "str") to list


            Because of this, you need to do the conversion explicitly, whether what you want is concatenation or addition:



            >>> 'Total: ' + str(123)
            'Total: 123'
            >>> int('456') + 789
            1245


            However, there is a better way. Depending on which version of Python you use, there are three different kinds of string formatting available2, which not only allow you to avoid multiple + operations:



            >>> things = 5




            >>> 'You have %d things.' % things # % interpolation
            'You have 5 things.'




            >>> 'You have things.'.format(things) # str.format()
            'You have 5 things.'




            >>> f'You have things things.' # f-string (since Python 3.6)
            'You have 5 things.'


            ... but also allow you to control how values are displayed:



            >>> value = 5
            >>> sq_root = value ** 0.5
            >>> sq_root
            2.23606797749979




            >>> 'The square root of %d is %.2f (roughly).' % (value, sq_root)
            'The square root of 5 is 2.24 (roughly).'




            >>> 'The square root of v is sr:.2f (roughly).'.format(v=value, sr=sq_root)
            'The square root of 5 is 2.24 (roughly).'




            >>> f'The square root of value is sq_root:.2f (roughly).'
            'The square root of 5 is 2.24 (roughly).'


            Whether you use % interpolation, str.format(), or f-strings is up to you: % interpolation has been around the longest (and is familiar to people with a background in C), str.format() is often more powerful, and f-strings are more powerful still (but available only in Python 3.6 and later).



            Another alternative is to use the fact that if you give print multiple positional arguments, it will join their string representations together using the sep keyword argument (which defaults to ' '):



            >>> things = 5
            >>> print('you have', things, 'things.')
            you have 5 things.
            >>> print('you have', things, 'things.', sep=' ... ')
            you have ... 5 ... things.


            ... but that's usually not as flexible as using Python's built-in string formatting abilities.




            1 Although it makes an exception for numeric types, where most people would agree on the 'right' thing to do:



            >>> 1 + 2.3
            3.3
            >>> 4.5 + (5.6+7j)
            (10.1+7j)


            2 Actually four ... but template strings are rarely used and somewhat awkward.






            share|improve this answer















            The problem here is that the + operator has (at least) two different meanings in Python: for numeric types, it means "add the numbers together":



            >>> 1 + 2
            3
            >>> 3.4 + 5.6
            9.0


            ... and for sequence types, it means "concatenate the sequences":



            >>> [1, 2, 3] + [4, 5, 6]
            [1, 2, 3, 4, 5, 6]
            >>> 'abc' + 'def'
            'abcdef'


            As a rule, Python doesn't implicitly convert objects from one type to another1 in order to make operations "make sense", because that would be confusing: for instance, you might think that '3' + 5 should mean '35', but someone else might think it should mean 8 or even '8'.



            Similarly, Python won't let you concatenate two different types of sequence:



            >>> [7, 8, 9] + 'ghi'
            Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
            TypeError: can only concatenate list (not "str") to list


            Because of this, you need to do the conversion explicitly, whether what you want is concatenation or addition:



            >>> 'Total: ' + str(123)
            'Total: 123'
            >>> int('456') + 789
            1245


            However, there is a better way. Depending on which version of Python you use, there are three different kinds of string formatting available2, which not only allow you to avoid multiple + operations:



            >>> things = 5




            >>> 'You have %d things.' % things # % interpolation
            'You have 5 things.'




            >>> 'You have things.'.format(things) # str.format()
            'You have 5 things.'




            >>> f'You have things things.' # f-string (since Python 3.6)
            'You have 5 things.'


            ... but also allow you to control how values are displayed:



            >>> value = 5
            >>> sq_root = value ** 0.5
            >>> sq_root
            2.23606797749979




            >>> 'The square root of %d is %.2f (roughly).' % (value, sq_root)
            'The square root of 5 is 2.24 (roughly).'




            >>> 'The square root of v is sr:.2f (roughly).'.format(v=value, sr=sq_root)
            'The square root of 5 is 2.24 (roughly).'




            >>> f'The square root of value is sq_root:.2f (roughly).'
            'The square root of 5 is 2.24 (roughly).'


            Whether you use % interpolation, str.format(), or f-strings is up to you: % interpolation has been around the longest (and is familiar to people with a background in C), str.format() is often more powerful, and f-strings are more powerful still (but available only in Python 3.6 and later).



            Another alternative is to use the fact that if you give print multiple positional arguments, it will join their string representations together using the sep keyword argument (which defaults to ' '):



            >>> things = 5
            >>> print('you have', things, 'things.')
            you have 5 things.
            >>> print('you have', things, 'things.', sep=' ... ')
            you have ... 5 ... things.


            ... but that's usually not as flexible as using Python's built-in string formatting abilities.




            1 Although it makes an exception for numeric types, where most people would agree on the 'right' thing to do:



            >>> 1 + 2.3
            3.3
            >>> 4.5 + (5.6+7j)
            (10.1+7j)


            2 Actually four ... but template strings are rarely used and somewhat awkward.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Dec 27 '16 at 17:10

























            answered Sep 4 '14 at 22:28









            Zero PiraeusZero Piraeus

            32.4k18 gold badges109 silver badges131 bronze badges




            32.4k18 gold badges109 silver badges131 bronze badges







            • 2





              This answer is great in that it provides both background info and multiple solutions, but the actual solutions are buried in the middle of a wall of text. It would benefit from a TLDR at the beginning (as a form of progressive disclosure).

              – Helen
              Dec 29 '16 at 20:10






            • 8





              @Helen this canonical Q/A is consciously written as a bait & switch – the question has a "gimme teh codez" style, while the answer makes a point of not immediately providing a "gimme teh codez" solution. I disagree that the inverted pyramid / progressive disclosure approach is a good one for beginner-level instruction; it improves the apparent productivity of bad programmers (who will indeed "dr" the "tl" remainder) at the expense of those who will later maintain their code. I'd rather help potentially great programmers than definitively awful ones, and try to contribute accordingly to SO.

              – Zero Piraeus
              Dec 29 '16 at 21:22











            • Great answer. I learn something new today.

              – alpeshpandya
              Apr 5 '17 at 19:21












            • 2





              This answer is great in that it provides both background info and multiple solutions, but the actual solutions are buried in the middle of a wall of text. It would benefit from a TLDR at the beginning (as a form of progressive disclosure).

              – Helen
              Dec 29 '16 at 20:10






            • 8





              @Helen this canonical Q/A is consciously written as a bait & switch – the question has a "gimme teh codez" style, while the answer makes a point of not immediately providing a "gimme teh codez" solution. I disagree that the inverted pyramid / progressive disclosure approach is a good one for beginner-level instruction; it improves the apparent productivity of bad programmers (who will indeed "dr" the "tl" remainder) at the expense of those who will later maintain their code. I'd rather help potentially great programmers than definitively awful ones, and try to contribute accordingly to SO.

              – Zero Piraeus
              Dec 29 '16 at 21:22











            • Great answer. I learn something new today.

              – alpeshpandya
              Apr 5 '17 at 19:21







            2




            2





            This answer is great in that it provides both background info and multiple solutions, but the actual solutions are buried in the middle of a wall of text. It would benefit from a TLDR at the beginning (as a form of progressive disclosure).

            – Helen
            Dec 29 '16 at 20:10





            This answer is great in that it provides both background info and multiple solutions, but the actual solutions are buried in the middle of a wall of text. It would benefit from a TLDR at the beginning (as a form of progressive disclosure).

            – Helen
            Dec 29 '16 at 20:10




            8




            8





            @Helen this canonical Q/A is consciously written as a bait & switch – the question has a "gimme teh codez" style, while the answer makes a point of not immediately providing a "gimme teh codez" solution. I disagree that the inverted pyramid / progressive disclosure approach is a good one for beginner-level instruction; it improves the apparent productivity of bad programmers (who will indeed "dr" the "tl" remainder) at the expense of those who will later maintain their code. I'd rather help potentially great programmers than definitively awful ones, and try to contribute accordingly to SO.

            – Zero Piraeus
            Dec 29 '16 at 21:22





            @Helen this canonical Q/A is consciously written as a bait & switch – the question has a "gimme teh codez" style, while the answer makes a point of not immediately providing a "gimme teh codez" solution. I disagree that the inverted pyramid / progressive disclosure approach is a good one for beginner-level instruction; it improves the apparent productivity of bad programmers (who will indeed "dr" the "tl" remainder) at the expense of those who will later maintain their code. I'd rather help potentially great programmers than definitively awful ones, and try to contribute accordingly to SO.

            – Zero Piraeus
            Dec 29 '16 at 21:22













            Great answer. I learn something new today.

            – alpeshpandya
            Apr 5 '17 at 19:21





            Great answer. I learn something new today.

            – alpeshpandya
            Apr 5 '17 at 19:21













            6














            TL;DR



            1. either: print("You have " + str(things) + " things.") (the old
              school way)


            2. or: print("You have things.".format(things)) (the new pythonic
              and recommended way)



            A bit more verbal explanation:

            Although there is anything not covered from the excellent @Zero Piraeus answer above, I will try to "minify" it a bit:

            You cannot concatenate a string and a number (of any kind) in python because those objects have different definitions of the plus(+) operator which are not compatible with each other (In the str case + is used for concatenation, in the number case it is used to add two numbers together).
            So in order to solve this "misunderstanding" between objects:



            1. The old school way is to cast the number to string with the
              str(anything) method and then concatenate the result with another
              string.

            2. The more pythonic and recommended way is to use the format method which is very versatile (you don't have to take my word on it, read the documentation and this article)

            Have fun and do read the @Zero Piraeus answer it surely worth your time!






            share|improve this answer




















            • 2





              This answer adds nothing new.

              – Ethan Furman
              Apr 5 '17 at 15:45











            • On the bright side, if you delete your answer now you'll get a badge for it (don't recall the name, but it's for deleting an answer with at least 3 upvotes).

              – Ethan Furman
              Apr 5 '17 at 15:49






            • 3





              @EthanFurman I think you are looking for this :) stackoverflow.com/help/badges/37/disciplined

              – Adam
              Apr 5 '17 at 19:00






            • 1





              @Ethan Furman There is nothing that can really be added to that answer, I just tried to minify it a bit and please the demand for a TL;DR from Helen! The canonical is the Zero Piraeus answer by far!

              – John Moutafis
              Apr 5 '17 at 19:08















            6














            TL;DR



            1. either: print("You have " + str(things) + " things.") (the old
              school way)


            2. or: print("You have things.".format(things)) (the new pythonic
              and recommended way)



            A bit more verbal explanation:

            Although there is anything not covered from the excellent @Zero Piraeus answer above, I will try to "minify" it a bit:

            You cannot concatenate a string and a number (of any kind) in python because those objects have different definitions of the plus(+) operator which are not compatible with each other (In the str case + is used for concatenation, in the number case it is used to add two numbers together).
            So in order to solve this "misunderstanding" between objects:



            1. The old school way is to cast the number to string with the
              str(anything) method and then concatenate the result with another
              string.

            2. The more pythonic and recommended way is to use the format method which is very versatile (you don't have to take my word on it, read the documentation and this article)

            Have fun and do read the @Zero Piraeus answer it surely worth your time!






            share|improve this answer




















            • 2





              This answer adds nothing new.

              – Ethan Furman
              Apr 5 '17 at 15:45











            • On the bright side, if you delete your answer now you'll get a badge for it (don't recall the name, but it's for deleting an answer with at least 3 upvotes).

              – Ethan Furman
              Apr 5 '17 at 15:49






            • 3





              @EthanFurman I think you are looking for this :) stackoverflow.com/help/badges/37/disciplined

              – Adam
              Apr 5 '17 at 19:00






            • 1





              @Ethan Furman There is nothing that can really be added to that answer, I just tried to minify it a bit and please the demand for a TL;DR from Helen! The canonical is the Zero Piraeus answer by far!

              – John Moutafis
              Apr 5 '17 at 19:08













            6












            6








            6







            TL;DR



            1. either: print("You have " + str(things) + " things.") (the old
              school way)


            2. or: print("You have things.".format(things)) (the new pythonic
              and recommended way)



            A bit more verbal explanation:

            Although there is anything not covered from the excellent @Zero Piraeus answer above, I will try to "minify" it a bit:

            You cannot concatenate a string and a number (of any kind) in python because those objects have different definitions of the plus(+) operator which are not compatible with each other (In the str case + is used for concatenation, in the number case it is used to add two numbers together).
            So in order to solve this "misunderstanding" between objects:



            1. The old school way is to cast the number to string with the
              str(anything) method and then concatenate the result with another
              string.

            2. The more pythonic and recommended way is to use the format method which is very versatile (you don't have to take my word on it, read the documentation and this article)

            Have fun and do read the @Zero Piraeus answer it surely worth your time!






            share|improve this answer















            TL;DR



            1. either: print("You have " + str(things) + " things.") (the old
              school way)


            2. or: print("You have things.".format(things)) (the new pythonic
              and recommended way)



            A bit more verbal explanation:

            Although there is anything not covered from the excellent @Zero Piraeus answer above, I will try to "minify" it a bit:

            You cannot concatenate a string and a number (of any kind) in python because those objects have different definitions of the plus(+) operator which are not compatible with each other (In the str case + is used for concatenation, in the number case it is used to add two numbers together).
            So in order to solve this "misunderstanding" between objects:



            1. The old school way is to cast the number to string with the
              str(anything) method and then concatenate the result with another
              string.

            2. The more pythonic and recommended way is to use the format method which is very versatile (you don't have to take my word on it, read the documentation and this article)

            Have fun and do read the @Zero Piraeus answer it surely worth your time!







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 1 '17 at 16:42

























            answered Mar 29 '17 at 20:44









            John MoutafisJohn Moutafis

            13.1k4 gold badges39 silver badges64 bronze badges




            13.1k4 gold badges39 silver badges64 bronze badges







            • 2





              This answer adds nothing new.

              – Ethan Furman
              Apr 5 '17 at 15:45











            • On the bright side, if you delete your answer now you'll get a badge for it (don't recall the name, but it's for deleting an answer with at least 3 upvotes).

              – Ethan Furman
              Apr 5 '17 at 15:49






            • 3





              @EthanFurman I think you are looking for this :) stackoverflow.com/help/badges/37/disciplined

              – Adam
              Apr 5 '17 at 19:00






            • 1





              @Ethan Furman There is nothing that can really be added to that answer, I just tried to minify it a bit and please the demand for a TL;DR from Helen! The canonical is the Zero Piraeus answer by far!

              – John Moutafis
              Apr 5 '17 at 19:08












            • 2





              This answer adds nothing new.

              – Ethan Furman
              Apr 5 '17 at 15:45











            • On the bright side, if you delete your answer now you'll get a badge for it (don't recall the name, but it's for deleting an answer with at least 3 upvotes).

              – Ethan Furman
              Apr 5 '17 at 15:49






            • 3





              @EthanFurman I think you are looking for this :) stackoverflow.com/help/badges/37/disciplined

              – Adam
              Apr 5 '17 at 19:00






            • 1





              @Ethan Furman There is nothing that can really be added to that answer, I just tried to minify it a bit and please the demand for a TL;DR from Helen! The canonical is the Zero Piraeus answer by far!

              – John Moutafis
              Apr 5 '17 at 19:08







            2




            2





            This answer adds nothing new.

            – Ethan Furman
            Apr 5 '17 at 15:45





            This answer adds nothing new.

            – Ethan Furman
            Apr 5 '17 at 15:45













            On the bright side, if you delete your answer now you'll get a badge for it (don't recall the name, but it's for deleting an answer with at least 3 upvotes).

            – Ethan Furman
            Apr 5 '17 at 15:49





            On the bright side, if you delete your answer now you'll get a badge for it (don't recall the name, but it's for deleting an answer with at least 3 upvotes).

            – Ethan Furman
            Apr 5 '17 at 15:49




            3




            3





            @EthanFurman I think you are looking for this :) stackoverflow.com/help/badges/37/disciplined

            – Adam
            Apr 5 '17 at 19:00





            @EthanFurman I think you are looking for this :) stackoverflow.com/help/badges/37/disciplined

            – Adam
            Apr 5 '17 at 19:00




            1




            1





            @Ethan Furman There is nothing that can really be added to that answer, I just tried to minify it a bit and please the demand for a TL;DR from Helen! The canonical is the Zero Piraeus answer by far!

            – John Moutafis
            Apr 5 '17 at 19:08





            @Ethan Furman There is nothing that can really be added to that answer, I just tried to minify it a bit and please the demand for a TL;DR from Helen! The canonical is the Zero Piraeus answer by far!

            – John Moutafis
            Apr 5 '17 at 19:08











            2














            Python 2.x




            1. 'You have %d things.' % things [1]


            2. 'You have things.'.format(things) [2]

            Python 3.6+




            1. 'You have %d things.' % things [1]


            2. 'You have things.'.format(things) [2]


            3. f'You have things things.' [3]


            Reference



            1. printf-style String Formatting

            2. Built-in types -> str.format

            3. Formatted string literals





            share|improve this answer























            • This adds nothing whatsoever to the existing answer.

              – Zero Piraeus
              Apr 2 '17 at 20:30






            • 3





              @ZeroPiraeus: No it does. Ever heard of 'readability'?

              – ngub05
              Apr 7 '17 at 13:13






            • 1





              And just because someone answered a question before me, it doesn't mean that I can approach it, with my own take (the way I think best describes the answer). If you think that's wrong, I think that'a not more wrong than downvoting someone's answer because you also have an answer for the same question.

              – ngub05
              Apr 7 '17 at 13:16















            2














            Python 2.x




            1. 'You have %d things.' % things [1]


            2. 'You have things.'.format(things) [2]

            Python 3.6+




            1. 'You have %d things.' % things [1]


            2. 'You have things.'.format(things) [2]


            3. f'You have things things.' [3]


            Reference



            1. printf-style String Formatting

            2. Built-in types -> str.format

            3. Formatted string literals





            share|improve this answer























            • This adds nothing whatsoever to the existing answer.

              – Zero Piraeus
              Apr 2 '17 at 20:30






            • 3





              @ZeroPiraeus: No it does. Ever heard of 'readability'?

              – ngub05
              Apr 7 '17 at 13:13






            • 1





              And just because someone answered a question before me, it doesn't mean that I can approach it, with my own take (the way I think best describes the answer). If you think that's wrong, I think that'a not more wrong than downvoting someone's answer because you also have an answer for the same question.

              – ngub05
              Apr 7 '17 at 13:16













            2












            2








            2







            Python 2.x




            1. 'You have %d things.' % things [1]


            2. 'You have things.'.format(things) [2]

            Python 3.6+




            1. 'You have %d things.' % things [1]


            2. 'You have things.'.format(things) [2]


            3. f'You have things things.' [3]


            Reference



            1. printf-style String Formatting

            2. Built-in types -> str.format

            3. Formatted string literals





            share|improve this answer













            Python 2.x




            1. 'You have %d things.' % things [1]


            2. 'You have things.'.format(things) [2]

            Python 3.6+




            1. 'You have %d things.' % things [1]


            2. 'You have things.'.format(things) [2]


            3. f'You have things things.' [3]


            Reference



            1. printf-style String Formatting

            2. Built-in types -> str.format

            3. Formatted string literals






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 2 '17 at 20:27









            ngub05ngub05

            3333 silver badges14 bronze badges




            3333 silver badges14 bronze badges












            • This adds nothing whatsoever to the existing answer.

              – Zero Piraeus
              Apr 2 '17 at 20:30






            • 3





              @ZeroPiraeus: No it does. Ever heard of 'readability'?

              – ngub05
              Apr 7 '17 at 13:13






            • 1





              And just because someone answered a question before me, it doesn't mean that I can approach it, with my own take (the way I think best describes the answer). If you think that's wrong, I think that'a not more wrong than downvoting someone's answer because you also have an answer for the same question.

              – ngub05
              Apr 7 '17 at 13:16

















            • This adds nothing whatsoever to the existing answer.

              – Zero Piraeus
              Apr 2 '17 at 20:30






            • 3





              @ZeroPiraeus: No it does. Ever heard of 'readability'?

              – ngub05
              Apr 7 '17 at 13:13






            • 1





              And just because someone answered a question before me, it doesn't mean that I can approach it, with my own take (the way I think best describes the answer). If you think that's wrong, I think that'a not more wrong than downvoting someone's answer because you also have an answer for the same question.

              – ngub05
              Apr 7 '17 at 13:16
















            This adds nothing whatsoever to the existing answer.

            – Zero Piraeus
            Apr 2 '17 at 20:30





            This adds nothing whatsoever to the existing answer.

            – Zero Piraeus
            Apr 2 '17 at 20:30




            3




            3





            @ZeroPiraeus: No it does. Ever heard of 'readability'?

            – ngub05
            Apr 7 '17 at 13:13





            @ZeroPiraeus: No it does. Ever heard of 'readability'?

            – ngub05
            Apr 7 '17 at 13:13




            1




            1





            And just because someone answered a question before me, it doesn't mean that I can approach it, with my own take (the way I think best describes the answer). If you think that's wrong, I think that'a not more wrong than downvoting someone's answer because you also have an answer for the same question.

            – ngub05
            Apr 7 '17 at 13:16





            And just because someone answered a question before me, it doesn't mean that I can approach it, with my own take (the way I think best describes the answer). If you think that's wrong, I think that'a not more wrong than downvoting someone's answer because you also have an answer for the same question.

            – ngub05
            Apr 7 '17 at 13:16











            -1














            str.format()



            Another alternative is using str.format() method to concatenate an int into a String.



            In your case:




            Replace




            print("You have " + things + " things.")



            With




            print("You have things".format(things))


            Bonus: for multiple concatenation



            if you have



            first = 'rohit'
            last = 'singh'
            age = '5'
            print("My Username is ".format(first,age,last))





            share|improve this answer



























              -1














              str.format()



              Another alternative is using str.format() method to concatenate an int into a String.



              In your case:




              Replace




              print("You have " + things + " things.")



              With




              print("You have things".format(things))


              Bonus: for multiple concatenation



              if you have



              first = 'rohit'
              last = 'singh'
              age = '5'
              print("My Username is ".format(first,age,last))





              share|improve this answer

























                -1












                -1








                -1







                str.format()



                Another alternative is using str.format() method to concatenate an int into a String.



                In your case:




                Replace




                print("You have " + things + " things.")



                With




                print("You have things".format(things))


                Bonus: for multiple concatenation



                if you have



                first = 'rohit'
                last = 'singh'
                age = '5'
                print("My Username is ".format(first,age,last))





                share|improve this answer













                str.format()



                Another alternative is using str.format() method to concatenate an int into a String.



                In your case:




                Replace




                print("You have " + things + " things.")



                With




                print("You have things".format(things))


                Bonus: for multiple concatenation



                if you have



                first = 'rohit'
                last = 'singh'
                age = '5'
                print("My Username is ".format(first,age,last))






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered May 10 at 7:46









                Rohit SinghRohit Singh

                4,2462 gold badges33 silver badges38 bronze badges




                4,2462 gold badges33 silver badges38 bronze badges















                    protected by Jim Fasarakis Hilliard Nov 18 '16 at 20:13



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?



                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript