You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数中无法为参数追加字符串的问题求助

问题修复方案

你的代码存在三个关键问题,导致输出不符合预期:

  1. 字符串拼接后未赋值回变量:Python里字符串是不可变类型,website + '/sitemap.xml'只会生成一个新字符串,但不会修改原website变量的值,必须把拼接结果重新赋值给website才能更新它。
  2. 函数调用参数未加引号:https://example.com不是合法的Python字符串字面量,必须用单引号或双引号包裹,否则会触发语法错误。
  3. 未处理网址末尾带斜杠的情况:如果输入的网址是https://example.com/,直接拼接会得到https://example.com//sitemap.xml,这种格式不符合规范,需要先去除末尾的斜杠再拼接。

基础修复版代码

def webparser(website):
    if 'sitemap.xml' not in website:
        # 将拼接后的新字符串赋值回website变量
        website = website + '/sitemap.xml'
    print(website)

# 参数必须用引号包裹成字符串
webparser("https://example.com")

更健壮的版本(处理末尾斜杠)

def webparser(website):
    if 'sitemap.xml' not in website:
        # 先移除网址末尾所有斜杠,再拼接路径
        website = website.rstrip('/') + '/sitemap.xml'
    print(website)

webparser("https://example.com")
webparser("https://example.com/")

运行上述代码后,两种输入都会输出https://example.com/sitemap.xml,符合预期。

内容的提问来源于stack exchange,提问作者Robert Carmichael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 23:00:14