在Python中如何将制表符(\t)添加或插入到列表中

huangapple go评论114阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月8日 21:07:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432174.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定