使用Python替换上次出现的字符串
拆分字符串后,我需要替换上一次出现的字符串 我尝试了下面的方法,但它给出了不正确的输出,如1.120 下面是我尝试过的代码使用Python替换上次出现的字符串,python,replace,split,increment,last-occurrence,Python,Replace,Split,Increment,Last Occurrence,拆分字符串后,我需要替换上一次出现的字符串 我尝试了下面的方法,但它给出了不正确的输出,如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.spli
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,据我所知,您需要这样的输出:
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
太复杂了。只需存储拆分的输出,进行更改,然后使用方法返回所需的字符串。根据更新的问题进行编辑,您还需要事先处理一些额外的字符。假设您只想在一个变量之后增加该部分。在应用拆分逻辑之前,您可以只跟踪剩余变量中的额外字符
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
下面的代码有效,我引用了@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)
也许您可以发布更多输入和期望输出的示例,以便更清楚地了解您正在尝试执行的操作。如果y=1.19-test,则不起作用。给定错误值error:以10为基数的int的文本无效:“test”。我需要的输出是1.20-testI,无论如何,我都不希望它能与这样的输入一起工作。您可能需要编辑您的问题或提出新问题。需要在拆分字符串之后替换最后一次出现的字符串,很明显,这样的输入不是最后一次出现。应在问题中添加此输入。已更新问题。。请帮我接电话this@moong好的,更新了我的答案。它起作用了。。。谢谢@Parithosh SinghIt,如果我们有y=1.19-test,它将不工作。给定错误值error:以10为基数的int的文本无效:“test”。我需要的输出是1.20-test,然后修改上面的代码来处理-它会工作的