In a Python program, I am trying to modify a string under a specific condition:
X = ('4c0')
Sig = ['a', 'b', 'c', 'e']
Sig is a list. Additionally, I have a tuple:
T = (4,'d',5)
If the second element (T[1]) is not in Sig, I must create another string, starting from X:
- as T[1] ('d') is not in Sig, T[2] must replace T[0] in X ('5' replacing '4');
- the last element in X must be added by 1 ('1' replacing '0').
In this case, the desired result should be:
Y = ('5c1')
I made this code but it is not add any string to 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)))
Any ideas how I could solve this problem?
CodePudding user response:
You need to be more clear as to what the conditions are if this is a one-time requirement you can use -
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'
CodePudding user response:
There are a lot of missing conditions in your problem statement (e.g. what to do if 'd' was in Sig, How to handle values past 9, what if X[0] is not the same as T[0], what if X[2] is equal to T[2])
For the example given a simple string format should suffice:
X = ('4c0')
Sig = ['a', 'b', 'c', 'e']
T = (4,'d',5)
if T[1] not in Sig:
Y = f"{T[2]}{X[1]}{int(X[2]) 1}"
print(Y) # 5c1