Python如何实现截取字符串最后10位,类似Excel的RIGHT函数功能?
Python实现字符串保留最后10位的方法
Python的字符串负索引切片可以直接满足该需求,无需额外判断长度,核心语法为:result = 待处理字符串[-10:]
原理:切片规则中负索引代表从字符串末尾倒序取值,当字符串长度≤10时,[-10:]会直接返回完整原字符串;当长度>10时,自动截取最后10位字符,完全匹配需求逻辑。
具体使用示例
- 长数字转字符串截取场景
input_val = 221234567890 str_val = str(input_val) output = str_val[-10:] print(output) # 输出结果:1234567890
- 短字符串场景
short_val = "abcde" output = short_val[-10:] print(output) # 输出结果:abcde
如果你需要和Excel公式逻辑对齐,显式写长度判断,也可以封装成函数:
def take_last_10(s: str) -> str: if len(s) > 10: return s[-10:] return s
内容的提问来源于stack exchange,提问作者Jonathan Vega
相关产品推荐
相关产品推荐

