-2

拆分字符串后,我需要替换最后一次出现的字符串

我尝试了以下方法,但它给出了不正确的输出,例如1.120

下面是我尝试过的代码。

y = "1.19-test"


if '-' in y:
    splt = (int(y.split('-')[0][-1]) + 1)
    str = y[::-1].replace(y.split('-')[0][-1], str(splt)[::-1], 1)[::-1]
    print str
else:
    splt = (int(y.split('.')[-1]) + 1)
    str = y[::-1].replace(y.split('-')[0][-1], str(splt)[::-1], 1)[::-1]
    print str

我得到的输出就像1.120-test. 但在这里我需要输出为1.20-test

4

3 回答 3

0

根据我的理解,你需要这样的东西:

y = "1-19"

str1 = ''
if '-' in y:
    splt = y.split('-')
    str1 = "%s-%s"%(splt[0], int(splt[-1])+1)
else:
    splt = y.split('.')
    str1 = "%s.%s"%(splt[0], int(splt[-1])+1)
print str1
于 2019-02-13T11:45:13.190 回答
0

太复杂。只需存储拆分的输出,进行更改,然后使用.join方法取回所需的字符串。编辑根据更新的问题,您还需要事先处理一些额外的字符。假设您只想增加 a 之后的部分,.您可以在应用拆分逻辑之前跟踪leftover变量中的额外字符。

y = "1.19-test"
leftover = ''
if '-' in y:
    temp_y, leftover = y[:y.index('-')], y[y.index('-'):]
else:
    temp_y = y

split_list = temp_y.split('.')
split_list[-1] = str(int(split_list[-1]) + 1) #convert last value to int, add 1, convert result back to string.
result = '.'.join(split_list) #joins all items in the list using "."
result += leftover #add back any leftovers
print(result)
#Output:
1.20-test
于 2019-02-13T11:45:25.323 回答
0

下面的代码有效,我参考了@Paritosh Singh 代码。

y = "1.19"
if '-' in y:
    temp = y.split('-')[0]
    splitter = '.'
    split_list = temp.split(splitter)
    split_list[-1] = str(int(split_list[-1]) + 1)
    result = splitter.join(split_list)
    print(result)
    print result+'-'+y.split('-')[1]

else:
    splitter = '.'
    split_list = y.split(splitter)
    split_list[-1] = str(int(split_list[-1]) + 1)
    result = splitter.join(split_list)
    print(result)
于 2019-02-13T13:23:30.627 回答