输出不带whitespce的字符串

时间:2016-11-22 18:44:04

标签: python python-2.7

我的节目:

def string_splosion(str):
    j=1
    c=len(str)
    i=0
    s=''
    while(i<c):
        s=s+(str[:i+j])
        i=i+1
        print s


print("Enter a string:")
s=raw_input()
string_splosion(s)

Sample input:Code
Expected output:CCoCodCode
My output:
Enter a string:
code
c co cod code

有没有人可以解释一下如何删除空间并获得 Python2.7.12

的预期输出 CCoCodCode

非常感谢!!!

2 个答案:

答案 0 :(得分:1)

目前,您将分别打印每个迭代。虽然你可以通过稍微改变逻辑来让你的例子起作用,但对于Python魔术来说这是一件容易的事:

>>> s = 'Code'
>>> ''.join(s[:i+1] for i in range(len(s)))
'CCoCodCode'

答案 1 :(得分:0)

您可以尝试以下方法:

def string_data(str):
  result= ""
  for x in range(len(str)):
    result = result + str[:x+1]
  return result

string_data('code')