【问题标题】:Modifying a string under a specific condition在特定条件下修改字符串
【发布时间】:2021-10-03 04:12:13
【问题描述】:

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

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

【问题讨论】:

标签: python string tuples


【解决方案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'

【讨论】:

    【解决方案2】:

    您的问题陈述中有很多缺失的条件(例如,如果 'd' 在 Sig 中该怎么办,如何处理超过 9 的值,如果 X[0] 与 T[0] 不同怎么办,如果 X[2] 等于 T[2] 会怎样)

    对于给出一个简单字符串格式的示例就足够了:

    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
    

    【讨论】:

    • 对不起,我没有提到它。没有高于 9 的值。
    猜你喜欢
    • 1970-01-01
    • 2019-10-09
    • 2018-12-02
    • 2021-03-05
    • 2016-09-09
    • 1970-01-01
    • 2019-10-26
    • 2020-01-20
    • 1970-01-01
    相关资源
    最近更新 更多