You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中替代Java/C++的索引式for循环并提取邮箱域名

用Python替代Java/C++索引式for循环并提取邮箱域名

一、Python中替代Java/C++式索引for循环的写法

Java/C++里的索引遍历循环:

for(i = 0; i < listName.length; i++)

在Python中可以通过range()配合len()实现完全等价的逻辑:

for i in range(len(listName)):
    # 通过listName[i]访问对应索引的元素

range(len(listName))会生成从0到列表长度-1的整数序列,和原循环的索引遍历逻辑完全一致。

二、提取邮箱域名的正确实现

你现有代码的多层嵌套循环逻辑混乱,重复遍历整个字符串,导致无法精准截取目标内容。以下提供两种可行方案:

方法1:用字符串内置方法(最简洁)

利用Python字符串的split()方法直接分割,一步到位:

email = input("Please enter an email: ")
# 先按@分割取后半段,再按.分割取第一段
domain = email.split('@')[1].split('.')[0]
print(domain)

输入jason@gmail.com时,会直接输出gmail。

方法2:用索引式循环(对应你想要的Java/C++循环替代方案)

如果要通过索引遍历的方式实现,步骤如下:

  1. 找到@的位置,确定域名起始点
  2. 从@的下一个位置开始遍历,找到第一个.的位置
  3. 截取两个位置之间的字符串
email = input("Please enter an email: ")
at_index = -1
dot_index = -1

# 遍历找@的索引
for i in range(len(email)):
    if email[i] == '@':
        at_index = i
        break

# 从@的下一个位置开始找第一个.的索引
for i in range(at_index + 1, len(email)):
    if email[i] == '.':
        dot_index = i
        break

# 输出结果
if at_index != -1 and dot_index != -1:
    print(email[at_index + 1 : dot_index])

这段代码用了和Java/C++一致的索引循环逻辑,同样能正确提取gmail。


内容的提问来源于stack exchange,提问作者Jonathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:55:14