【问题标题】:Meaning of the second bracket [] in the print statement in python [duplicate]python中print语句中第二个括号[]的含义[重复]
【发布时间】:2020-04-17 13:28:46
【问题描述】:

下面是代码。 我不明白[::-1][:-1]中最后一个括号的意思,你怎么能同时写两个括号。我知道第一个切片括号颠倒了字符串的顺序,但是第二个是做什么的呢?

for i in range(n,0,-1):
    temp = list(alphabets[:n][i-1:])
    print('-'.join(temp[::-1][:-1]+temp).center(4*n-3,'-'))

感谢合作!

【问题讨论】:

  • 这能回答你的问题吗? Understanding slice notation。您可以根据需要尽可能多地链接切片 - 它们从左到右处理,结果从每个切片传递到下一个切片。

标签: python string formatting slice reverse


【解决方案1】:

为了回答你的问题,我将使用一个例子:

list = [1,2,3,4,5]

正如您所说,第一个括号将反转您的列表。 然后,你会得到这样的结果:[5,4,3,2,1]

在该列表上,您将进行切片:[:-1]。结果就是[5,4,3,2]

括号里的意思是一样的: [<startIndex>:<endIndex>:<how to go through>]

有关<how to go through>部分的更多信息,请在此处阅读:https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多