【问题标题】:string inside string inside string in python format [duplicate]python格式的字符串内字符串内的字符串[重复]
【发布时间】:2020-11-21 09:04:53
【问题描述】:

我想把字符串放在字符串里面,如下所示

f"{home.select_one('td a[title="Odds"]')['href']}"

但它返回错误

SyntaxError: invalid syntax

【问题讨论】:

  • 变量名是什么?
  • 使用三引号。
  • 变量名:home
  • 我已经在原帖@Ravanelli 中回答了

标签: python web-scraping beautifulsoup


【解决方案1】:

转义引号:

print("{home.select_one('td a[title=\"Odds\"]')['href']}")

【讨论】:

  • SyntaxError: f-string 表达式部分不能包含反斜杠
  • 我没有提到 f-strings,这是针对一般和原始字符串的
  • @Ravanelli:不是这样。 Wasif 提供的生产线有效。因此,您正在做其他事情。
【解决方案2】:

使用.format

In [117]: home = BeautifulSoup("""<td><a title="Odds" href="https://url"></td>""", "html.parser")

In [118]: "{}".format(home.select_one('td a[title=\"Odds\"]')['href'])
Out[118]: 'https://url'

或者使用三引号

In [123]: f"""
     ...: {home.select_one('td a[title="Odds"]')['href']}
     ...:
     ...: """.strip()
Out[123]: 'https://url'

【讨论】:

    猜你喜欢
    • 2019-03-04
    • 2010-10-17
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    相关资源
    最近更新 更多