简体   繁体   English

string.split错误? 蟒蛇

[英]string.split error? python

a = string.split("Test Test2 Test3"," ")

This returns an error: 这将返回错误:

Message File Name   Line    Position    
Traceback               
    <module>    C:\pyWiz.py 43      
AttributeError: 'module' object has no attribute 'split'                

Yes, I imported the string module. 是的,我导入了字符串模块。 Why is this happening? 为什么会这样呢?

Use: 采用:

a = 'Test Test2 Test3'.split(' ')

(ie split method of str type). (即str类型的split方法)。 string.split is deprecated in 2.x and gone in 3.x. 在2.x中不推荐使用string.split ,而在3.x中使用。

string is a module while you were looking for the class/type object str . 在寻找类/类型对象str string是一个模块。 I would recommend doing this though: 我建议尽管这样做:

a = "Test Test2 Test3".split()

为什么不只是"Test Test2 Test3".split()

a = "Test Test2 Test3".split(" ")
>>> a = 'jetpack ferret pizza lawyer'.split()
>>> a
['jetpack', 'ferret', 'pizza', 'lawyer']

>>> b = 'jetpack ferret pizza lawyer'
>>> b.split()
['jetpack', 'ferret', 'pizza', 'lawyer']
>>> b
'jetpack ferret pizza lawyer'

>>> c = """very   
looooooooooooooooooooooong string      with trailing random whitespace    """
>>> c = c.split()
>>> c
['very', 'looooooooooooooooooooooong', 'string', 'with', 'trailing', 'random', 'whitespace']

>>> d = 'dog;_cat;_fish;_'.split(';_')
>>> d
['dog', 'cat', 'fish', '']

It is to note that most times you don't need to specify the separator (which can be made of mutiple characters). 请注意,大多数情况下,您无需指定分隔符(可以由多个字符组成)。

If we simplify, giving no arguments to the split function gets you rid of all whitespace (ie spaces, tabs, newlines, returns), and this is a preferred behavior to work with input from a file, a shell etc, and also notably in a most common use of this idiom: hard coding a list of strings saving some annoying typing of commas and quotes. 如果我们简化了操作,不给split函数提供任何参数将使您摆脱所有空白(即空格,制表符,换行符,返回值),这是与文件,shell等的输入配合使用的首选行为,尤其是在这个习惯用法最常见的用法是:对字符串列表进行硬编码,以节省一些烦人的逗号和引号输入。

Also be aware you're gonna get empty strings in your list if: 另请注意,如果发生以下情况,您将在列表中得到空字符串:

  • input string ends or starts with one or more characters you defined as separator (see my last example) 输入字符串以您定义为分隔符的一个或多个字符结尾或开头(请参见我的上一个示例)

  • there's more than one separator between group of characters you want to get 您要获得的一组字符之间有多个分隔符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM