Python Forum

Full Version: Simple question on tab
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Absolute newbie and just starting to learn.

I cannot work out why the first two programs below work, but the third does not!

1.
 person_name = "Albert"
       print (person_name) 
2.
 print ("\tAlbert") 
3.
 person_name = "Albert"
       print (\tperson_name) 
ERROR on 3rd program is: SyntaxError: unexpected character after line continuation character

Thanks
First point is that indentation in Python is incredibly important, so your first example should not have the second line indented.
In your second example, \t means tab as it is inside the quoted string
In your third example, since the backslash is not inside a quoted string it is expected that this is a line break. If you have a very long line of code in Python you can break it into multiple lines by putting a backslash at the end of each line up to the last.
print(\
      'Hello')
Works. So, your code adds a t and a bumch of other characters after the backslash which Python objects to.
Thanks for replying. Sorry the indents are not on my original code - got transferred over to this question somehow.

So how would I tab a VARIABLE then? E.g. set a variable to a text string, then tab that variable.

Thanks again!
Several ways to do. You can concatenate, as in
myvar = "Albert"
bigger_var = '\t' + myvar
print(bigger_var)
Output:
Albert
Or, preferred, use format strings
myvar = "Albert"
print("\t{}".format(myvar))
Or, IMHO, best of all (there are lots of style opinions)
myvar = "Albert"
print(f"\t{myvar}")
To me the last one is most readable and maintainable.
Perfect explanation thank you so much!