python - 为什么 replace() 方法不能正常工作但字符串拼接工作
问题描述
最近我遇到了一个我无法理解的错误输出。
我正在解决一个问题,如果字符串中的前一个字符按字母顺序在当前字符之前,那么我必须将当前字符大写。另一方面,如果当前字符按字母顺序在前一个字符之前,则当前字符小写。如果两者相同,则无需执行任何操作。
例如:
Input : ab cB GG
Output : aB cb GG
这是我的代码:
def transformSentence(sentence):
for i in range(len(sentence)):
s = sentence[i]
p = sentence[i-1]
if i ==0 or s == ' ' or p == ' ':
continue
if s == p:
continue
elif ord(s.lower()) > ord(p.lower()):
sentence = sentence.replace(sentence[i], sentence[i].upper())
elif ord(s.lower()) < ord(p.lower()):
sentence = sentence.replace(sentence[i], sentence[i].lower())
return sentence
print(transformSentence('ab cB GG'))
我为这个代码块得到的输出是:
ab cb GG
如果您注意到上面的输出,则第二个块中的replace()elif
有效!(大写 b 更改为小写,因为它在 c 之前的首字母)
当我使用string slicing
andconcatenation
而不是replace()
像下面这样时,它在两个块上都能完美运行,并给我预期的输出:
sentence = sentence[:i] + sentence[i].upper() + sentence[i+1:]
我需要知道为什么replace()方法在第一个块中不起作用elif
但在第二个块中起作用。
解决方案
Replace 更新了句子中各处的字母。
推荐阅读
- python - 用换行符分隔 python 元组
- docker - 在 Docker 容器中构建 .NET Core 项目时,如何将 GitVersion 集成到 TeamCity 中?
- php - 来自 Web 服务的 PHP 字符串比较
- python - 每次使用 python 启动系统时制作本地键盘记录器发送电子邮件
- date - Flutter/Dart - 在输入表单中格式化日期
- java - Java中根据年龄和性别随机生成团队
- c# - SQL Server 存储过程访问以检索数据并显示给用户
- python - 使用 Matplotlib 在 Python 中绘制数据框 - 水平条形图
- python - 在python中连接服务器和客户端时出现超时错误
- python - 以特定格式对字符串或整数数组进行排序