你能在一行上调用多个方法吗?

2024-10-05 14:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我想:

texta = text.lower()
textacopy1 = texta.replace(string.punctuation, ' ')
textacopy2 = textacopy1.split(' ')

有没有一种更干净的方法可以在不需要分配多个变量的情况下做到这一点?

如果2.7和3.x之间有差异,我更喜欢3.x的解释。


Tags: 方法textstring情况差异lowerreplacesplit
3条回答
result = text.lower().replace(string.punctuation, ' ').split(' ')

伟大的python带来了巨大的责任:不要滥用这个特性!

PEP 8中编码的规范最大行长度是80个字符, 分割方法链的标准方法是从一个点开始新行:

result = text.lower().replace(string.punctuation, ' ')
        .split(' ')

你可以用一个变量来做,你不必用多个变量,这会引起混乱。代码也会更干净。你也可以一行一行的。

text = text.lower()
text = text.replace(string.punctuation, ' ')
text = text.split(' ')

你也可以一行一行的

text = text.lower().replace(string.punctuation, ' ').split(' ')

对于正则表达式,它甚至更干净

    In [132]: split_str = re.compile(r'[{} ]+'.format(string.punctuation))

    In [133]: split_str.split("You can do it with one variable you don't have to use multiple variable which can cause confusion. Also code will be much cleaner. You can do it in one line also.")
    Out[133]: 
    ['You',
     'can',
     'do',
     'it',
.....
     'in',
     'one',split_string = 
     'line',
     'also',
     '']

相关问题 更多 >