How to use "\t" on a variable in Python

I am teaching myself Python with a book, and, in one of the assignments I need to make a program to strip whitespace before and after a variable. It also says to use the \n and \t escape characters.

I can get strip(), lstrip() and rstrip() to work but \t and \n are giving me trouble.

Is there a way to use \t on a variable?

I tried this:

name = " shane waxwing "
print(\tname)

It only works on strings, like this:

print("\tshane waxwing")
8

2 Answers

if you are looking for a tab or a newline in front of the variable you could use f-strings:

print(f"\n{variable}")

or, if you prefer you could use string concatenation:

print('\t'+variable)

NOTE: this works only if the variable in question is a string else you would need to convert it to a str object before:

print('\t'+str(variable))

or

print(''.join("\t",str(variable)))
1

\t is used to provide a whitespace equal to a tab. for example:

Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"

Output:

Twinkle, twinkle, little star,
How I wonder what you are! Up above the world so high, Like a diamond in the sky. 

Twinkle, twinkle, little star, How I wonder what you are

Solution:

print("Twinkle, twinkle, little star,\n\tHow I wonder what you are!\n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star,\n\tHow I wonder what you are")

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like