【问题标题】:How do I use a loop to join strings together and return the result? [closed]如何使用循环将字符串连接在一起并返回结果? [关闭]
【发布时间】:2014-05-18 14:51:17
【问题描述】:

我的代码

def joinStrings(*stringList):

    for gallery in stringList:
        return gallery

joinStrings('john', 'ate', 'a', 'sandwich')

如何解决这个问题,让 for 循环加入字符串?我似乎无法弄清楚我做错了什么。

【问题讨论】:

  • 你为什么不用str.join?
  • 嗯,您期望加入的位置在哪里?

标签: python string loops


【解决方案1】:

你会想要this:

''.join(['john', 'ate', 'a', 'sandwich'])

您可以在第一个 '' 之间放置所需的分隔符(空格、逗号、...)或不放置分隔符

您可以在 for 循环中执行此操作,但效率会很低,因为字符串“加法”/连接不能很好地扩展(但当然可以):

def joinStrings(mylist)
  s = ""
  for item in mylist:
     s += item
     s += "" #Place your seperator here
  return s

johnlist = 'john', 'ate', 'a', 'sandwich'
joinStrings(johnlist)

【讨论】:

    【解决方案2】:
    def joinStrings(stringList):
        output = ""
        for gallery in stringList:
            output += gallery
            output += " "
        output = output[:-1] #remove last space
        return output
    
    joinStrings('john', 'ate', 'a', 'sandwich')
    

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 2020-05-07
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      相关资源
      最近更新 更多