字符串字符删除需求:删除字符串倒数第二位数字
如何删除数字中的倒数第二位数字?
Hey there! Let's solve this problem where we need to strip the second-to-last digit from a given number. Based on your examples:
- Input: 23001 → Expected Output: 2301
- Input: 662001 → Expected Output: 66201
- Input: 11001 → Expected Output: 1101
I'll share two straightforward approaches to achieve this—one using string manipulation (super intuitive) and another using pure arithmetic operations (no string conversion needed).
方法一:字符串切片法
This is the easiest way to handle the problem, since string slicing makes it trivial to pick specific parts of the string:
def remove_second_last_digit(num): num_str = str(num) # 拼接除倒数第二位外的所有字符 result_str = num_str[:-2] + num_str[-1:] return int(result_str) # 测试你的示例输入 sample_nums = [23001, 662001, 11001] for num in sample_nums: print(f"Input: {num} → Output: {remove_second_last_digit(num)}")
运行这段代码后,你会得到完全符合预期的结果:
Input: 23001 → Output: 2301 Input: 662001 → Output: 66201 Input: 11001 → Output: 1101
方法二:纯数字运算
如果你不想把数字转成字符串,也可以用基础数学运算实现相同效果:
def remove_second_last_digit(num): # 提取最后一位数字 last_digit = num % 10 # 去掉原数字的最后两位 truncated_num = num // 100 # 重新组合结果:截断后的数字补位 + 最后一位 return truncated_num * 10 + last_digit # 测试函数 sample_nums = [23001, 662001, 11001] for num in sample_nums: print(f"Input: {num} → Output: {remove_second_last_digit(num)}")
这个方法的逻辑拆解:
num % 10分离出最后一位数字(比如 23001 % 10 = 1)num // 100移除最后两位数字(比如 23001 // 100 = 230)- 把截断后的数字乘以10腾出位置,再加上最后一位数字(230 * 10 + 1 = 2301)
额外提示
两种方法都假设输入的数字至少有2位(毕竟要删除倒数第二位)。如果可能遇到位数不足的情况,可以加个简单判断来优雅处理:
def remove_second_last_digit(num): num_str = str(num) if len(num_str) < 2: return num # 或者根据需求抛出异常,拒绝无效输入 return int(num_str[:-2] + num_str[-1:])
内容的提问来源于stack exchange,提问作者Mathieu L
相关产品推荐
相关产品推荐

