【问题标题】:Can't find split() method or replacement in string module in python 3.4.1? [duplicate]在 python 3.4.1 的字符串模块中找不到 split() 方法或替换? [复制]
【发布时间】:2014-09-23 00:51:03
【问题描述】:

我正在尝试一些文本操作,但遇到了错误:

wordlist = string.split(" ")
AttributeError: 'module' object has no attribute 'split'

我已经像这样导入了字符串模块:

import string

当我列出字符串模块中可用的方法时,split() 没有按预期出现。

['ChainMap', 'Formatter', 'Template', '_TemplateMetaclass', '__builtins__', 
'__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', 
'__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase',
'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 
'whitespace']

我不确定这是否是我的错误,或者是否有新的拆分方法。如何通过它们之间的空格拆分字符串?

【问题讨论】:

    标签: python string python-3.x split attributeerror


    【解决方案1】:

    您不必导入字符串模块进行拆分。您可以简单地对您的字符串变量运行拆分

    str = "testing 1 2 3"
    print str.split(" ") #or str.split()
    

    输出

    ['testing', '1', '2', '3']
    

    【讨论】:

    • 感谢您的回答:)
    • 在 python 2 中我从字符串导入 split 在 python 3 中我很懒所以我做了 split = lambda a,b: a.split(b)
    【解决方案2】:

    string.split 在 2.x 中已弃用并在 3.x 中消失。

    只要做:

    yourStringName.split(' ')
    

    参考string.split error? python

    【讨论】:

    • 好的,谢谢你的信息!
    猜你喜欢
    • 2023-04-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多