python - 范围递增中的 For 循环
问题描述
为什么 for 循环中的“c”不递增?
def solution(s):
for c in range(len(s)):
if s[c] == s[c].upper():
s = s[:c] + ' ' + s[c:]
c += 1
return s
print(solution('helloWorld'))
输出应该是"hello World"
,但是,当我添加一个空格时," "
我也会增加c
,但它不起作用。电流输出为'hello World'
解决方案
你可以想到:
for c in range(len(s)):
作为c
每个循环迭代的范围“设置”。范围跟踪它所处的迭代次数。
我想你的意思是这样的:
def solution(s):
c = 0
while c < len(s):
if s[c] == s[c].upper():
s = s[:c] + ' ' + s[c:]
c += 1
c += 1
return s
推荐阅读
- ruby-on-rails - 在 cygwin 上为 sassc 安装包时出错
- c# - `SkiaSharp.SKBitmap` 中的 `InstallPixels()` 和 `SetPixels()` 有什么区别?
- sql - 重组 Impala/Hive 中使用子查询在表中创建新列的查询
- html - Microsoft Excel IE 自动化 - 从下拉清单中选择项目
- c - 4 个不同的函数相互传递指针,但由于某种原因,我的程序永远不会运行到最后,我不太清楚为什么
- layout - Kivy 将小部件添加到预定义布局
- perl - 如何使用 perl 文件添加版权行以写入示例 perl 文件
- ios - 如何控制 iOS 工具栏上 UIBarButtonItem 控件的布局?
- r - 删除一列具有重复值的行,但仅当最新行具有另一列的特定值时
- c# - 无法在 .Net 核心中跟踪类型的实例?