【问题标题】:How would I insert a word into a string?如何在字符串中插入一个单词?
【发布时间】:2021-10-06 03:53:06
【问题描述】:

我有一个字符串https://www.exampleurl.com/ 如何在字符串中间插入一个单词,使其看起来像这样:https://www.subdomain.exampleulr.com/

如果我这样做,我知道我可以插入单词:

url = 'https://www.exampleurl.com/'
url[:12] + 'subdomain'

它打印我https://www.subdomain,但我不知道如何动态打印字符串的其余部分,因此它会调整到附加到字符串的子域。 我的目标是让最终结果看起来像下面的https://www.subdomain.exampleurl.com/

【问题讨论】:

标签: python


【解决方案1】:
url = 'https://www.exampleurl.com/'
content = url.split("www.")

url = content[0] + "www." + "subdomain." + content[1]

【讨论】:

    【解决方案2】:
    url = 'https://www.exampleurl.com/'
    text = url.split(".")
    
    url =  text[0] + '.subdomain.' + text[1] + '.' + text[2]
    

    最终输出:https://www.subdomain.exampleurl.com/

    【讨论】:

      【解决方案3】:

      最好在第一个.上拆分:

      l = url.split('.', 1)
      l[0] + '.subdomain.' + l[1]
      
      ## OR if subdomain is a variable:
      f'{l[0]}.{subdomain}.{l[1]}'
      

      输出:'https://www.subdomain.exampleurl.com/'

      【讨论】:

        【解决方案4】:
        url = 'https://www.exampleurl.com/'
        url = url[:12] + 'subdomain' + url[11:]
        print(url)
        

        结果:

        https://www.subdomain.exampleurl.com/
        

        无论子域是什么,它都可以工作。

        【讨论】:

          【解决方案5】:

          使用替换(一次)

          url = 'https://www.exampleurl.com/'
          url = url.replace(".", ".subdomain.", 1)   # only replaces first "." to 
                                                     # get desured result
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-09-25
            相关资源
            最近更新 更多