【问题标题】:And operator to check equality between strings [duplicate]和运算符检查字符串之间的相等性[重复]
【发布时间】:2019-08-29 17:00:09
【问题描述】:

我正在尝试检查字符串的元素在左侧和右侧是否有空格。我正在尝试在 Python 中使用 and 运算符,但出现此错误:

unsupported operand type(s) for &: 'str' and 'str'

这是我的代码:

for i in range(0,len(s_sentence)-1):
    if (s_sentence[i-1]==' ' & s_sentence[i+1]==' '):
        [...]

我该如何解决这个问题?谢谢!

【问题讨论】:

  • and替换你的&
  • 使用 and 关键字。
  • 附带说明:如果range 等于0,则不必指定起点,因为它是默认起点。如您所见,print(range(0,12)) 将给出与print(range(12)) 完全相同的结果
  • 请注意,"a " 字符串无法给出您期望的结果。从 1 开始你的范围,而不是 0

标签: python operator-keyword


【解决方案1】:
if (s_sentence[i-1]==' ' and s_sentence[i+1]==' '):

& 不是您要查找的运算符,and 是。

旁注:& 在 Python 中进行位与

【讨论】:

    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    相关资源
    最近更新 更多