python - 尝试在python中一次搜索2个字符
问题描述
我刚刚回到python,我试图通过一个字符串一次搜索两个字符,然后用其他东西替换它们。例如在字符串“aah”中搜索字符串“aa”并将其替换为其他内容,例如“xx”,但是当我尝试运行它时,它说类型必须是字符串,而不是 int。这是我的代码,任何帮助将不胜感激,谢谢
test = input("enter words to encrypt\n")
#print(test)
#change a letter
def changea(test):
#print(test)
outp = ""
for i in test:
if i & i+1 == "aa":
outp += "x"
else:
outp += i
print(outp)
changea(test)
解决方案
理想情况下,您应该使用replace
or re.sub
。但是,如果您致力于使用循环,您可以尝试以下方法:
def changea(test):
pairs = zip(test, test[1:] + "$")
out = ""
for x, y in pairs:
if x == "a" and y == "a":
out += "x"
next(pairs) # Skip the next iteration
else:
out += x
return out
changea("Maary haad aa little laamb")
#'Mxry hxd x little lxmb'
推荐阅读
- sql - SSIS 中从 IBM DB2 到 SQL 的特殊字符问题
- python - 您传递给模型的 Numpy 数组列表不是模型在 3d 数组上预期的大小
- c# - .NET 模拟 Ruby 的 CableReady + Stimulus Reflex?/ SPA 在 Websockets 上使用 HTML
- sas - SAS - 如果那么做条件
- python - 当我收到来自外部 API 的 400 响应时,我应该抛出哪个异常?
- arrays - for 循环中的 else 语句将不起作用
- python - 带有 beam.dataframe.io.read_fwf 的数据流:缺少 Ptransforms
- javascript - 单击特定按钮时不断弹出打印屏幕
- amadeus - 如何使用 Amadeus API 在航班报价搜索中设置 maxFlightTime?
- azure-data-explorer - 我可以从配置文件设置 Kusto 集群吗?