python - 在没有替换功能的情况下替换python中的字符
问题描述
def replace_characters(the_string):
new_string = ''
for i in range(len(the_string)-1):
slice_string = the_string[i: i + 2]
if slice_string == 'ph':
new_string += 'b
else:
new_string = the_string
print(new_string)
if __name__ == "__main__":
the_string = input('What string do you want to process?')
replace_characters(the_string)
对于输出,如果我有 ph 的输入,我可以得到 φ,但当字符串较长时(比如电话)就不行了。我想得到 φone
解决方案
我看到三个问题
(1)else
替换所有字符串,但应添加一个字符,如new_string += the_string[i]
.
(2) 使用for
-loop 不能跳过第二个字符ph
,它可以h
与下一个字符一起使用,或者将其添加到新字符串中。如果你有 statemant 的变化,ho
那么它会pho
像ph
+ho
(3) 使用len(the_string)-1
它可能会跳过最后一个字符。
我的版本
def replace_characters(the_string):
new_string = ''
i = 0
while i < len(the_string):
slice_string = the_string[i: i+2]
if slice_string == 'ph':
new_string += '\u03d5'
i += 2
elif slice_string == 'th':
new_string += '\u03b8'
i += 2
elif slice_string == 'ch':
new_string += '\u03c7'
i += 2
else:
new_string += the_string[i]
i += 1
print(new_string)
if __name__ == "__main__":
the_string = 'phone'
replace_characters(the_string)
推荐阅读
- java - 如何使用 querydsl 获取子字段?
- apache-spark - Spark Streaming 窗口使用
- python - gmpy2中如何准确判断一个mpfr数是否为整数?
- django - 我无法在 django 视图中作为组织登录
- javascript - 如何在 AJAX 函数完全执行之前修复 jQuery Promise .then() 被调用?
- sharepoint - 文档级别的共享点权限?可能是个愚蠢的问题
- python - 读一个“。” 分隔文件并使用 python 创建 SQL 查询
- python - 列值不在 padas 数据框中的索引中
- arrays - 使用指针数组将输入和输出输入文件
- node.js - 设置秘密时,express-jwt 秘密应设置错误