报错: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)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值