python - 在特定条件下修改字符串
问题描述
在 Python 程序中,我试图在特定条件下修改字符串:
X = ('4c0')
Sig = ['a', 'b', 'c', 'e']
Sig 是一个列表。另外,我有一个元组:
T = (4,'d',5)
如果第二个元素 (T[1]) 不在 Sig 中,我必须创建另一个字符串,从 X 开始:
- 由于 T[1] ('d') 不在 Sig 中,因此 T[2] 必须替换 X 中的 T[0]('5' 替换 '4');
- X 中的最后一个元素必须加 1('1' 替换 '0')。
在这种情况下,期望的结果应该是:
Y = ('5c1')
我制作了这段代码,但它没有向 Y 添加任何字符串:
Y = []
for i in TT: # TT has the tuple T
i = list(i)
if i[1] not in Sig:
for j in TT:
if type(j[2]) == str:
if i[1] == j[1]:
Y.append(j[2][0]+i[1]+str(int(j[2][2]+1)))
有什么想法可以解决这个问题吗?
解决方案
如果这是您可以使用的一次性要求,您需要更清楚条件是什么-
i = 1
if T[i] not in sig:
Y=list(X) # converting the string to a list in order to perform operations
Y[i-1] = T[i+1] # operation 1 [replace element at position -1 as compared to Tuple element position check]
Y[-1] = int(Y[-1])+1 # operation 2 [add 1 to the last element]
print(''.join(map(str, Y)))
'5c1'
推荐阅读
- java - 为什么 lambda 在抛出运行时异常时会更改重载?
- typescript - Typescript:通用类类型推断
- html - 如何防止chrome使用html css和js文件的缓存副本而不是angular 4中来自服务器的新构建数据
- sql-server - 使用 INTO Select 将一个表数据复制到另一个数据库中
- tensorflow - 如何通过张量流中的索引获取元素?
- javascript - 如何防止签名令牌用户通过浏览器开发工具访问 API 响应?
- c# - FTP 音频文件上传在 C# 中不起作用
- eos - eosjs 的 httpEndPoint 没有改变
- python - 使用 Python 将输出打印到文本文件 (.txt)
- django - Django 中的网络聊天应用程序