Usage of expandtabs built-in function of string in python

1. str.expandtabs()

Before entering this function, let's take a look:

str_1 = 'abc\tdef'
print(str_1)  # abc	def

str_2 = '\t'
print(len(str_2))  # 1

According to the print results, abc is one character away from def. 在字符串中\t的长度为1(The tab key is also \t, which is usually 4 characters in length. When we write a branch structure, we also often use the tab key to indent 4 characters in length)

The purpose of the str.expandtabs() function is to convert the tab symbols in the string \tinto spaces, and the specific number of spaces is determined by the parameter tabsize.

Misunderstanding: It is not the number of spaces in the parameter tabsize, the two are not equal. The number of parameters indicates how many characters are in a group: if the parameter tabsize = 6, then the string will be a group of characters with a length of 6; if the parameter tabsize is not written, the default tabsize = 8, then the string will be in length 8 characters are a group. Divides a string into groups of varying character lengths.

语法:str.expandtabs(tabsize)

若参数tabsize没有写,则默认tabsize = 8,那么\t转为的空格数 = 8 - \t前字符串的长度

Next, let's look at the case:
str = "runoob\t12345\tabc"
print(str.expandtabs())  
# runoob  12345   abc

Explanation:
The parameter here is not assigned a value, the default is 8, 参数tabsize=8 > \t前字符串的长度=6. Then the number of spaces converted from \t = 8 - the length of the string before \t.

runnob has 6 characters, the following \t is filled with 2 spaces
12345 has 5 characters, and the following \t is filled with 3 spaces

case:
str = "runoob\t12345\tabc"
print(str.expandtabs(2))  # runoob  12345 abc

print(str.expandtabs(3))  # runoob   12345 abc

print(str.expandtabs(4))  # runoob  12345   abc

print(str.expandtabs(5))  # runoob    12345     abc

print(str.expandtabs(6))  # runoob      12345 abc

Explanation: The parameter tabsize is equal to 2, 3, 4, 5, and 6 in turn, and the strings will be divided into groups with character lengths of 2, 3, 4, 5, and 6 respectively.


tabsize=2, runoob character length is 6, can be divided into 3 groups, ru, no, ob each is a group, the first \t is a group, then it represents brother Lian space, 1234 is divided into two groups, 5 and a space group Team.

tabsize=4, runo is a group, ob plus two spaces is a group, so the first \t is two spaces; 1234 is a group, 5 can only be a group with three spaces, so the second \t is three spaces

tabsize=6, runnoob is divided into one group, since runoob has no remaining letters for the first \t, so a single group
represents 6 spaces, and 12345 can be grouped with one less length, so the second \t at this time t stands for a space.


insert image description here

Guess you like

Origin blog.csdn.net/m0_71422677/article/details/132220486