1

I'm trying to run a script for exercise 3.3 in the book Think Python:

Problem: Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.

I've worked a few kinks out of script so far and right now I have this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def right_justify(s):
    print ‘ ‘ * (70 - len(s)) + s

right_justify(‘allen’)

and when I try to run it I get the following error:

 File "/Users/Jon/Documents/Python/Chapter 3/right justify.py", line 5
    print ‘ ‘ * (70 - len(s)) + s
          ^
SyntaxError: invalid syntax

What mistake did I make and what should I do to fix this script?

Brisanth
  • 13
  • 1
  • 3
  • SHould be: `print ' ' * (70 - len(s)) + s` – Marcin Jan 09 '15 at 03:14
  • You may want to consider switching text editors. If you're using an editor like `TextEdit` that isn't designed for code, you're likely to end up with funny issues like this one. I personally recommend [Sublime](http://www.sublimetext.com/), but there are alot of other great editors out there. – rickcnagy Jan 09 '15 at 04:36
  • If you are on Python 3, you need additional parentheses: `print(' ' * (70 - len(s)) + s)` – tripleee Mar 17 '23 at 11:23

2 Answers2

3

The character is unrecognized by the parser. You need to use either apostrophes or quotation marks (' or ") for string literals:

print ' ' * (70 - len(s)) + s

For more information, see Strings literals in the documentation.

0

The character you're using

print ‘ ‘ * (70 - len(s)) + s

is a non-ascii apostrophe, and while you can use unicode literals in your code, you can't use them for single quotes. You need the ascii single quote, ', (also sometimes used as an apostrophe),

print ' ' * (70 - len(s)) + s

or a double quote:

print " " * (70 - len(s)) + s
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331