1

I am using ipython notebook in ubantu version 16.04 and I run this code,

word = 'Rushiraj'
length = 0
for char in 'rushiraj':
    length = length + 1
print('There are', length,'character')

I get this output: ('There are', 8, 'character')

What is the reason for this single quotes and round braces in output ?It should not be there !

Thomas K
  • 39,200
  • 7
  • 84
  • 86
R.Brahmbhatt
  • 67
  • 1
  • 3
  • 7

2 Answers2

4

The output you are seeing is due to the fact that you are using Python 2, but you're using the print syntax from Python 3. In Python 3, print is a function and takes arguments like other functions (as in print(...)).

In Python 2, print is a statement, and by using parentheses you are actually passing it a tuple as its first argument (so you are printing out the Python representation of a tuple).

You can fix this in two ways.

If you add from __future__ import print_function to the top of your file, then print will behave like it does in Python 3.

Alternately, you can call it like:

print 'There are', length,'character'
larsks
  • 277,717
  • 41
  • 399
  • 399
  • how can I switch to python 3 from python 2 ? @larsks – R.Brahmbhatt Nov 05 '16 at 02:10
  • He is obviously using Python 2, but indicates he wants to switch to Python 3. – Ukimiku Nov 05 '16 at 06:58
  • Perhaps I was tired and misread the comment. I thought it said the opposite last night, but there it is! @R.Brahmbhatt, that question is actually too big to answer in a comment. Depending on your system, you may be able to type `python3` and have it installed already, or you may need to figure out how to install a Python 3 interpreter, which varies between operating systems and linux distributions. – larsks Nov 05 '16 at 11:15
  • thank for reaching back but I find the solution @larsks I just set the python 3 as default but setting the alias ! – R.Brahmbhatt Nov 06 '16 at 20:23
0

You're printing a tuple (even though it may not appear that way at first glance), so the output is the repr of that tuple.

KingRadical
  • 1,282
  • 11
  • 8
  • I didn't say print called `__repr__`; I said the output is the repr of the tuple. `tuple.__str__` just calls `tuple.__repr__`. – KingRadical Nov 05 '16 at 02:00