【问题标题】:How does while loop works with string splicing to find out the length of the string?while循环如何与字符串拼接一起找出字符串的长度?
【发布时间】:2021-12-04 23:40:45
【问题描述】:

我遇到了以下代码,使用字符串拼接和while循环来查找字符串的长度:

    str='xyz'
    counter=0
    while str[counter:]: 

        counter+=1
    print(counter)

我无法理解将 str[counter:] 作为 while 循环的条件是如何工作的。 while 循环如何执行此操作。我不明白其中的逻辑。有人可以帮我解决这个问题吗 谢谢

【问题讨论】:

  • 了解编程语言可能会很方便

标签: string while-loop


【解决方案1】:

字符串基本上是一个字符数组,在您的情况下为 str[0] = x str[1] = y str[2] = z

所以while循环每次只打印字符串的一个字符,打印str[0]、str[1]、str[2]等等。 [counter:]你可以理解为这个数组的结尾,没有:会给你一个无限循环。

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    相关资源
    最近更新 更多