Python add or insert tab (\t) into list

Hi All,
I am new to python. I am trying to add a /t to a string variable and insert in to a list.
when I print the string, it prints with tab space.
When the same variable added to the list it prints \t. how to fix it.

str1="new_service_group"
src_grp="servicegroups\t\t\t\t"+str1
print("src_grp is = "+src_grp)
array=['define service{', 'host_name               host-a1p', 'service_description     Disk Space /var', 'use                     ch_rating_system', '}']
array.insert(len(array)-1,src_grp)
print(array)

output:

src_grp is = servicegroups				new_service_group
['define service{', 'host_name               host-a1p', 'service_description     Disk Space /var', 'use                     ch_rating_system', 'servicegroups\t\t\t\tnew_service_group', '}']

My advice (FWIW) is not to do that: if you want to present the contents of a list object, formatted in a particular way (be that with tab spaces, or whatever) then introduce the ‘formatting’ when you construct the output, rather then mixing the formatting with the data.

1 Like

Hi! Welcome to the Discourse and to Python programming!

What you’re seeing here is the difference between the string form and the representation. Inside a list, you’re seeing the representation (or “repr”) of the strings, which is designed to be similar to source code; it’s also meant to be unambiguous (you can’t confuse tabs and spaces when the tabs are shown as "\t").

So what you want here is to print out a series of things. That’s awesome, Python can do that for you! Here’s one way:

for line in array:
    print(line)

Or alternatively, you can join the parts together. Python has a slightly quirky way of spelling this, but there are good reasons for that:

service_config = " ".join(array)
print(service_config)

Give those two a try and see what you think of them. You may find that they’re not precisely what you want, but you can tweak from there.

Have fun with it!

To output object value along with its name one can use f-strings support a handy = specifier for debugging (introduced in Python 3.8):

>>> spam = "bacon and eggs"
>>> print(f"{spam=}")
spam='bacon and eggs'
>>> spam = 6
>>> print(f"{spam=}")
spam=6

Hi All,
Thanks for your replies. I got it resolved by using expandtabs()

str1="new_service_group"
src_grp="servicegroups\t\t\t\t"+str1
print("src_grp is = "+src_grp)
array=['define service{', 'host_name               host-a1p', 'service_description     Disk Space /var', 'use                     ch_rating_system', '}']
array.insert(len(array)-1,src_grp.expandtabs())
print(array)

I’ll try to format the values when I print it.