报错:AttributeError 之 str object has no attribute startwith

AttributeError: ‘str’ object has no attribute ‘startwith’

学习金角大王的re正则模块,敲代码遇到的问题:

1、需求:
打印电话号码字段

2、txt文件:
在这里插入图片描述
3、给出第一版代码:

f = open("7-module_re联系方式.txt")

phone_list = []
for line in f:
    name,sex,height,weight,phone = line.split()
    if phone.startwith("1"):
        phone_list.append(phone)

print(phone_list)

报错:

UnicodeDecodeError: 'gbk' codec can't decode byte 0xab in position 16: illegal multibyte sequence

这个地方简单,编码格式有问题,换成utf-8就好
修改之后的代码为:

f = open("7-module_re联系方式.txt",encoding="utf-8")

4、接着运行,又报错

AttributeError: 'str' object has no attribute 'startwith'

此时对比原视频代码,没发现什么问题
最后百度
找到这篇帖子

http://element-ui.cn/news/show-60748.aspx
此处未联系作者就转载了,如侵权,请联系,我会删掉

原因就是:
“注意函数名称书写要正确!
将startwith改为startswith即可!”

修改后的代码如下:

    if phone.startswith("1"):

最终运行成功,输出
[‘13131313131’, ‘11861234568’, ‘15825814736’, ‘18932145678’, ‘19632355669’]

最后贴上完整代码

f = open("7-module_re联系方式.txt",encoding="utf-8")

phone_list = []
for line in f:
    name,sex,height,weight,phone = line.split()
    if phone.startswith("1"):
        phone_list.append(phone)

print(phone_list)

猜你喜欢

转载自blog.csdn.net/Waste_youth/article/details/106278383