英文:
In Python how to add or insert tab (\t) into list
问题
I expect "servicegroups\t\t\t\tnew_service_group".
英文:
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 space.
When the same variable added/inserted to the list it prints \t. how to fix it.
Same works if if add space.
Please help me.
Code:
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', '}']
But I expect "servicegroups new_service_group"
答案1
得分: 0
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)
英文:
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)
Use the expandtabs()
method on your element for the tabs to print correctly
When you print element from a list, you use the repr method of the list object, not the one of the String object which is different.
Note that by doing expandtabs() on the object before adding it to the list, you are actually modifying the string added to the list by replacing /t
by the space equivalent.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论