首页 > 解决方案 > 在特定条件下修改字符串

问题描述

在 Python 程序中,我试图在特定条件下修改字符串:

X = ('4c0')
Sig = ['a', 'b', 'c', 'e']

Sig 是一个列表。另外,我有一个元组:

T = (4,'d',5)

如果第二个元素 (T[1]) 不在 Sig 中,我必须创建另一个字符串,从 X 开始:

在这种情况下,期望的结果应该是:

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)))

有什么想法可以解决这个问题吗?

标签: pythonstringtuples

解决方案


如果这是您可以使用的一次性要求,您需要更清楚条件是什么-

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'

推荐阅读