用Python解释[:0]

2024-10-01 09:36:24 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,所以在我因为非RTFM而被激怒之前,我知道[:0]在我的情况下:

s ="itsastring"
newS= []
newS[:0] = s

最终通过切片将s转换为列表。这是我的最终目标,但由于有Java背景,我不完全理解“[:0]中的“0”部分,也不完全理解为什么它被放在那里(我知道它大致意味着增加0).最后,Python如何知道我希望s的每个字符都是基于此语法的元素?我想理解它,以便能更清楚地记住它


Tags: 元素列表语法情况切片java字符news
3条回答

希望有帮助:

s ="itsastring"

#if you add any variable in left side then python will start slicing from there
#and slice to one less than last index assigned on right side
newS = s[:]

因此[:0]意味着将字符串从beggining分割到0字符串中的s元素(或者再次是第一个),结果是什么都没有。默认情况下,从第一个元素到最后一个元素进行切片,或者print(s[0:])print(s)相同

我建议您尝试在整个字符串中循环如下:

s = [x for x in "itsastring"]
print(s)

# result
['i', 't', 's', 'a', 's', 't', 'r', 'i', 'n', 'g']

如果ST是序列,S[a:b] = T将用T的元素替换S的索引ab-1的子序列
如果a == b,它将充当一个简单的插入。
而且{}与{}是一样的:所以它是在前面的一个简单插入

s = [11,22,33,44,55,66,77]
s[3:3] = [1,2,3] # insertion at position 3
print( s )

s = [11,22,33,44,55,66,77]
s[3:4] = [1,2,3] # deletion of element at position 3, and then insertion 
print( s )

s = [11,22,33,44,55,66,77]
s[3:6] = [1,2,3] # deletion of elements from position 3 to 5, and then insertion 
print( s )

s = [11,22,33,44,55,66,77]
s[:] = [1,2,3] # deletion of all elements, and then insertion : whole replacement 
print( s )

输出:

[11, 22, 33, 1, 2, 3, 44, 55, 66, 77]
[11, 22, 33, 1, 2, 3, 55, 66, 77]
[11, 22, 33, 1, 2, 3, 77]
[1, 2, 3]

相关问题 更多 >