Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple question on tab
#1
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
Reply
#2
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.
Reply
#3
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!
Reply
#4
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.
Reply
#5
Perfect explanation thank you so much!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple Question - ' defined as "a". ?' Ryan012 10 1,491 May-27-2023, 06:03 PM
Last Post: Ryan012
  Very simple question about filenames and backslashes! garynewport 4 1,832 Jan-17-2023, 05:02 AM
Last Post: deanhystad
  Python Tkinter Simple Multithreading Question AaronCatolico1 5 1,475 Dec-14-2022, 11:35 PM
Last Post: deanhystad
  A simple "If...Else" question from a beginner Serena2022 6 1,638 Jul-11-2022, 05:59 AM
Last Post: Serena2022
  Simple arithmetic question ebolisa 5 2,008 Dec-15-2021, 04:56 PM
Last Post: deanhystad
  Simple code question about lambda and tuples JasPyt 7 3,238 Oct-04-2021, 05:18 PM
Last Post: snippsat
Big Grin question about simple algorithm to my problem jamie_01 1 1,635 Oct-04-2021, 11:55 AM
Last Post: deanhystad
  Simple question 1234 4 2,228 Dec-04-2020, 12:29 PM
Last Post: DeaD_EyE
  Simple Timer Question cranberrica 3 2,141 Jun-22-2020, 06:29 PM
Last Post: cranberrica
  Simple question concerning python dot notation. miner_tom 1 1,876 Mar-24-2020, 05:20 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020