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.
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: