for example from a random input number by using input() i want to remove only a single number 5
note: if multiple 5's are there only 1 five should be removed, from left to right
examples:
- input = 555, output should be 55
- input = 599657, output should be 59967
- input = 6578, output should be 678
- input = 59959786, output should be 5999786
- input = 34567, output should be 3467
- input = 55, output should be 5
CodePudding user response:
Potentially split at the rightmost 5, then join back:
s = input()
print(''.join(s.rsplit('5', 1)))
Or reverse the string so we can use replace
and then reverse back:
s = input()
print(s[::-1].replace('5', '', 1)[::-1])
CodePudding user response:
Find the index of the right most 5, if it exists. Then slice the string, excluding that position
s = input()
i = s.rfind("5")
if i == -1:
print(s)
else:
print(s[:i] s[i 1:])
CodePudding user response:
Pretty sure it is not the best idea, but here we go:
def removeLast5(number):
string = str(number)
reverseList = list(reversed(list(string)))
check =False
for index, chr in enumerate(reverseList):
if chr == "5":
check = True
break
if check:
del reverseList[index]
return "".join(reversed(reverseList))
If you run the function such as removeLast5(425674345)
you will get 42567434
as a result.
CodePudding user response:
To do it using math only (i.e. without converting to string), you could make a recursive function:
def removeLast5(N):
return removeLast5(N//10)*10 N if N and N != 5 else N//10
for n in (555,599657,6578,59959786,34567,55):
print(n,"-->",removeLast5(n))
555 --> 55
599657 --> 59967
6578 --> 678
59959786 --> 5999786
34567 --> 3467
55 --> 5
If you're processing this as a string, you could use a regular expression with re.sub:
import re
N = input()
print( re.sub(r"5(?!.*5)",'',N) ) # replace 5 not followed by another 5