【问题标题】:How to substring a string without using slice and print function?如何在不使用切片和打印功能的情况下对字符串进行子串化?
【发布时间】:2020-11-12 07:22:00
【问题描述】:
make_substring(chars: str, start: int, stop: int, step: int)-> str

想要一种方法,它返回给定字符串的子字符串,该子字符串从开始索引(包括)开始,到停止索引(不包括)结束,每次迭代都会增加步骤字符。假设 start 和 stop 是非负的,而 step 是正的。也使用 for 循环。

def make_substring(chars: str, start: int, stop: int, step: int) -> str:
    c = chars
    s = ""
    if start + step < stop:
       for i in range(start, stop, step):
           s = c[start] + c[start + step]
       return s

# using test case:
make_substring("ABCD", 0, 3, 2) == "AC"

【问题讨论】:

  • 您不觉得在for 循环中没有使用i 很可疑吗?

标签: python for-loop substring


【解决方案1】:

这一行:

s = c[start] + c[start + step]

保持将s 设置为相同的两个字符,因为startstart + step 在循环中不会改变。它不累积字符,也不处理索引i处的字符。

那一行应该是:

s += c[i]

使用+= 使其附加到字符串,c[i] 是范围内的当前字符。

另外,去掉if 语句。即使start + step &gt; stop,您仍应在结果中包含start 处的字符。

def make_substring(chars: str, start: int, stop: int, step: int) -> str:
    s = ""
    for i in range(start, stop, step):
        if i >= len(chars):
            break // stop when we run out of characters
        s += chars[i]
    return s

不需要c 变量,只需使用chars 参数即可。

【讨论】:

  • 我尝试了make_substring("ABCD", 0, 3, 2),它返回了AC,正如预期的那样。
  • 感谢您的发帖。但是当我尝试显示时,它显示字符串索引超出范围的错误。
  • 我添加了一个检查 i 是否在字符串中。
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 2017-09-28
相关资源
最近更新 更多