【问题标题】:Not able to join a string properly in python无法在 python 中正确连接字符串
【发布时间】:2020-10-08 13:39:54
【问题描述】:

我无法正确加入字符串。

代码如下:

def mub(s):
 count = 1
 for i in range(len(s)):
     words = s[i] * count 
     list_of = list(words)
     print('-'.join(list_of),end='')
     count+=1
mub('Abcd')

它给了我这个作为输出: ab-bc-c-cd-d-d-d

但我想要的输出是这样的: a-bb-ccc-dddd

我认为错误是在for循环之后。

【问题讨论】:

    标签: python-3.x string list


    【解决方案1】:

    一种解决方案是使用- 保留要加入的字符串列表。例如:

    def mub(s):
     count = 1
     to_join = []
     for i in range(len(s)):
         to_join.append(s[i] * count)
         count+=1
     print('-'.join(to_join))
    
    mub('abcd')
    

    打印:

    a-bb-ccc-dddd
    

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多