Python如何获取字符串的最后10个元素?附邮箱后缀检测示例
Python字符串操作:获取末尾10个元素与邮箱后缀检测
一、获取字符串的最后10个元素
Python里不需要手动遍历计数来获取字符串长度,直接用负索引切片或者len()函数就能简洁实现:
- 方法1:负索引切片(推荐)
字符串的负索引从末尾开始计数,s[-10:]会直接返回字符串最后10个字符;如果字符串长度不足10,则返回整个字符串。
示例代码:input_str = "abc@gmail.com" last_10_chars = input_str[-10:] print(last_10_chars) # 输出:@gmail.com - 方法2:通过
len()计算索引
如果想用类似你提供的思路,正确写法是先获取字符串长度,再计算切片范围:
你提供的示例代码存在语法错误,input_str = "abc@gmail.com" str_len = len(input_str) last_10_chars = input_str[str_len-10:str_len] print(last_10_chars) # 输出:@gmail.comcount=1 for i in input不符合Python循环语法,完全没必要手动遍历计数,len()函数可以直接获取字符串长度。
二、检测输入值末尾是否包含'@gmail.com'
Python字符串内置的endswith()方法是最简便的解决方案,直接返回布尔值:
示例代码:
input_str = input("请输入邮箱地址:") if input_str.endswith('@gmail.com'): print("输入的地址末尾包含'@gmail.com'") else: print("输入的地址末尾不包含'@gmail.com'")
也可以用切片对比的方式实现,但endswith()更直观易读:
input_str = "abc@gmail.com" gmail_suffix = '@gmail.com' # 切片获取末尾与后缀长度相同的部分进行对比 if input_str[-len(gmail_suffix):] == gmail_suffix: print("包含指定后缀") else: print("不包含指定后缀")
内容的提问来源于stack exchange,提问作者Ronith
相关产品推荐
相关产品推荐

