【问题标题】:Traversal through a string with a loop in Python [duplicate]在Python中使用循环遍历字符串[重复]
【发布时间】:2017-07-15 22:54:05
【问题描述】:

我下面的代码不是通用的;它将每一行输出作为特殊情况处理。如何使用 while 或 for 语句获得相同的输出?

string = "Apple"
i = 0

one = string[0:i+1]
two = string[0:i+2]
three = string[0:i+3]
four = string[0:i+4]
five = string[0:i+5]

print(one)
print(two)
print(three)
print(four)
print(five)

我有以下结果:

A
Ap
App
Appl
Apple

【问题讨论】:

    标签: python


    【解决方案1】:

    请注意,您的变量 i 是无用的:您将其设置为 0,然后仅将其用于添加内容。转储它。

    这是循环索引的简单用法:

    for i in range(len(string)):
        print string[0:i+1]
    

    请注意,您可以从 print 语句中删除 0

    【讨论】:

      【解决方案2】:

      在 Python 中,我们可以遍历字符串来获取单个字符。

      output = ''
      for letter in 'Apple':
          output += letter
          print (output)
      

      【讨论】:

      • 您不需要在每条语句的末尾使用分号,尽管您产生了正确的输出,但您在每次迭代时都会不断地创建一个字符串。
      • 感谢您的评论。我知道我们创建了一个新字符串,但是字符串切片同样昂贵,而且我觉得可读性较差。
      【解决方案3】:

      使用 for 循环:

      for i in range(len(string)):
          print(string[0:i+1])
      

      带有一个while循环:

      j = 0
      while j < len(string):
          j += 1
          print(string[0:j])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-18
        • 1970-01-01
        • 2015-02-13
        • 1970-01-01
        • 2014-01-29
        • 2016-01-24
        • 2021-12-14
        • 1970-01-01
        相关资源
        最近更新 更多