为什么Python不想访问我的2项列表的第二项?

时间:2017-12-05 11:17:35

标签: python email

我正在尝试将格式为jim.smith-royal@smth.edu或jim.smith@smth.edu的电子邮件地址拆分为姓名和姓氏,以便吉姆和史密斯,或吉姆和史密斯皇室(带空格)介于两者之间)。 (我是初学者,所以我可能不是以最简单的方式做到这一点,但仍然)。

for row in votants:
    mail = row[1]
    full_name = mail.split('@')[0]
    prenom = full_name.split('.')[0]

    #The code works until here, full_name.split gives me ['jim','smith'] and prenom gives me 'jim'

    pre_name = full_name.split('.')
    nom = pre_name[1]

    #The problem is until here, but I kept the rest of my code for anyone who might have the same objective as me

    try:
        nom = nom.split('-')[0] + " " + nom.split('-')[1]
    except Exception:
        pass
    row.append(prenom)
    row.append(nom)

我得到“IndexError:list index超出范围”而不是给我'smith'这个名词。

1 个答案:

答案 0 :(得分:0)

我试过了:

mail = "jim.smith@smth.edu"
full_name = mail.split('@')[0]
prenom = full_name.split('.')[0]

#The code works until here, full_name.split gives me ['jim','smith'] and prenom gives me 'jim'

pre_name = full_name.split('.')
nom = pre_name[1]

#The problem is until here, but I kept the rest of my code for anyone who might have the same objective as me


print(full_name);
print(pre_name);
print(nom);
print(prenom);

并打印:

  • jim.smith

  • [' jim',' smith']

  • 史密斯

  • 吉姆

没有任何例外。

问题:

喜欢评论说:如果没有"。"在名称中使用(在@之前),您可能面临indexOutOfRange异常。

可能的解决方案:

在if-else块中包围它:

if len(pre_name) >= 2

或使用try-except:

try:
    nom = pre_name[1]
except IndexError:
    nom = pre_name[0];

或使用:

if "." in full_name: 
    pre_name = full_name.split('.')
    nom = pre_name[1]

常规调试:

先前使用print()

// works until here
pre_name = full_name.split('.')
print(pre_name) // if no '.' was used, you will see the array contains only 1 element
nom = pre_name[1] // problem here?