python上的字符串拆分
为什么字符串[1::2]的内部有一个4属性。所以必须是3个属性开始、结束、增量步骤。代码运行时没有任何错误。可以解释为什么字符串有4个属性而不是3个,它是相同的还是不同的 切片运算符的基本语法是python上的字符串拆分,python,string,split,Python,String,Split,为什么字符串[1::2]的内部有一个4属性。所以必须是3个属性开始、结束、增量步骤。代码运行时没有任何错误。可以解释为什么字符串有4个属性而不是3个,它是相同的还是不同的 切片运算符的基本语法是[开始:结束:步骤],其中end索引被排除在外。如果缺少这些参数中的任何一个,则使用默认值 比如说, n = int(input()) # number of strings for _ in range(n): string = input() print(string[::2], s
[开始:结束:步骤]
,其中end
索引被排除在外。如果缺少这些参数中的任何一个,则使用默认值
比如说,
n = int(input()) # number of strings
for _ in range(n):
string = input()
print(string[::2], string[1::2]) # print even letters, odd letters
some_string[:len(some_string)] # from 0 to the end of string(step=1 by default)
some_string[:len(some_string):1] # identical to the previous example
some_string[0:len(some_string):1] # also identical to the previous example
some_string[0:] # identical as well(end is len(some_string) by default here)
some_string[0::1] # identical to previous example
如您所见,如果未提供默认值,将使用默认值,这非常有用。我打赌我们所有人都宁愿写[:]
,也不愿写[0:len(string):1]
附言
如果缺少len(string)-1
和其他运算符,则此规则会略有更改。比如说,
n = int(input()) # number of strings
for _ in range(n):
string = input()
print(string[::2], string[1::2]) # print even letters, odd letters
some_string[:len(some_string)] # from 0 to the end of string(step=1 by default)
some_string[:len(some_string):1] # identical to the previous example
some_string[0:len(some_string):1] # also identical to the previous example
some_string[0:] # identical as well(end is len(some_string) by default here)
some_string[0::1] # identical to previous example
只有3个属性
1
(开始)、None
(结束)和2
(增量)