Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using \t on a variable in Python

So I am teaching myself Python with a book. In one of the assignments it asks me to make a program to get rid of whitespace before and after a variable. It also asks to use the \n and \t.

I can get the strip(), lstrip() and rstrip() methods to work just fine. It’s these \t and \n that are giving me trouble.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried this:

name = " shane waxwing "
print(\tname)

It only works on strings, like this:

print("\tshane waxwing")

I hope this makes sense. Thanks in advance ^_^

>Solution :

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading