Python List 初始化单个字符串时的注意事项

在Python中,使用list()初始化单个字符串会将其拆分成字符列表,而使用[]则保持原样。文章通过测试代码展示了这两种方法的不同效果,提醒在处理字符串时注意选择合适的初始化方式,以避免意外的字符拆分。
摘要由CSDN通过智能技术生成

在项目中手写遍历文件夹搜素文件时需要返回目标列表,发现 Python 初始化 List 列表时产生了与预期不一致的结果,特记录一下。

Python 初始化 List 列表可使用类型 list() 或者表达符号[]进行初始化,但是这两种初始化方式对单个字符串的处理并不一致,使用 list() 初始化单个字符串时会将字符串拆分为单个字符的列表,而使用 [] 则会保留为一个数组元素。通常情况下不对字符串进行拆分,因此建议不要省略 [] 符号。

测试代码:

a = ['hello']; p = 'world'; a.extend(p); print('p : {}, type : {};    a : {}, type : {}'.format(p, type(p), a, type(a)))
b = ['hello']; q = [p]    ; b.extend(q); print('q : {}, type : {};    b : {}, type : {}'.format(q, type(q), b, type(b)))
c = ['hello']; r = list(p); c.extend(r); print('r : {}, type : {};    c : {}, type : {}'.format(r, type(r), c, type(c)))
d = ['hello']; s = list(q); d.extend(s); print('s : {}, type : {};    d : {}, type : {}'.format(s, type(s), d, type(d)))

# output :
# p : world                    , type : <class 'str'> ;    a : ['hello', 'w', 'o', 'r', 'l', 'd'], type : <class 'list'>
# q : ['world']                , type : <class 'list'>;    b : ['hello', 'world']                , type : <class 'list'>
# r : ['w', 'o', 'r', 'l', 'd'], type : <class 'list'>;    c : ['hello', 'w', 'o', 'r', 'l', 'd'], type : <class 'list'>
# s : ['world'                ], type : <class 'list'>;    d : ['hello', 'world']                , type : <class 'list'>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值