Python 中的反斜杠 ('\') 本身是什么意思? [英] What does a backslash by itself ('\') mean in Python?

查看:60
本文介绍了Python 中的反斜杠 ('\') 本身是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 nltk 文档(http://www.nltk.org/_modules/nltk/sentiment/vader.html)

I found this code in the nltk documentation (http://www.nltk.org/_modules/nltk/sentiment/vader.html)

if (i < len(words_and_emoticons) - 1 and item.lower() == "kind" and \
            words_and_emoticons[i+1].lower() == "of") or \
            item.lower() in BOOSTER_DICT:
            sentiments.append(valence)
            continue

有人能解释一下 if 条件是什么意思吗?

Can someone explain what this if condition means?

推荐答案

行尾的反斜杠告诉 Python 将当前逻辑行扩展到下一个物理 行.请参阅行结构部分Python 参考文档:

A backslash at the end of a line tells Python to extend the current logical line over across to the next physical line. See the Line Structure section of the Python reference documentation:

两条或多条物理线可以使用以下方法连接成逻辑线反斜杠字符 (\),如下所示:当物理行以不是字符串文字或注释的一部分的反斜杠,它是加入以下形成一个单一的逻辑行,删除反斜杠和后面的行尾字符.例如:

2.1.5. Explicit line joining

Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:

if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1

还可以选择使用隐式行连接,通过使用圆括号或方括号或花括号;Python 不会结束逻辑行,直到它为每个左括号或大括号找到匹配的右括号或大括号.这是推荐的代码风格,你找到的示例应该写成:

There is also the option to use implicit line joining, by using parentheses or brackets or curly braces; Python will not end the logical line until it finds the matching closing bracket or brace for each opening bracket or brace. This is the recommended code style, the sample you found should really be written as:

if ((i < len(words_and_emoticons) - 1 and item.lower() == "kind" and
        words_and_emoticons[i+1].lower() == "of") or
        item.lower() in BOOSTER_DICT):
    sentiments.append(valence)
    continue

请参阅 Python 样式指南 (PEP 8)(但请注意例外情况;某些 Python 语句不支持 (...) 括号,因此在那里可以接受反斜杠).

See the Python Style Guide (PEP 8) (but note the exception; some Python statements don't support (...) parenthesising so backslashes are acceptable there).

请注意,Python 不是唯一使用反斜杠进行行连续的编程语言;bash、C 和 C++ 预处理器语法,Falcon、Mathematica 和 Ruby 也使用此语法来扩展行;请参阅维基百科.

Note that Python is not the only programming language using backslashes for line continuation; bash, C and C++ preprocessor syntax, Falcon, Mathematica and Ruby also use this syntax to extend lines; see Wikipedia.

这篇关于Python 中的反斜杠 ('\') 本身是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆