Python 已知字符串:s="ABCDABDCACDBCDABCBDACADBBCAD"。请按以下规则编写程序: (1)将s中的"B?D"替换为"1?2",?表示任意字母,替换后保留,例如:"BAC"、"BDC"分别替换为"1A2"、"1D2" (2)要求用循环结构实现
时间: 2023-12-04 14:41:49 浏览: 209
以下是Python代码,可以实现已知字符串s中的"B?D"替换为"1?2",?表示任意字母,替换后保留,例如:"BAC"、"BDC"分别替换为"1A2"、"1D2",并且使用循环结构实现:
```python
s = "ABCDABDCACDBCDABCBDACADBBCAD"
new_s = ""
i = 0
while i < len(s):
if s[i] == "B" and s[i+2] == "D":
new_s += "1" + s[i+1] + "2"
i += 3
else:
new_s += s[i]
i += 1
print(new_s)
```
阅读全文