2014-05-18 2 views
-3

내 코드어떻게 루프를 사용하여 문자열을 결합하고 결과를 반환합니까?

def joinStrings(*stringList): 

    for gallery in stringList: 
     return gallery 

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

어떻게이 for 루프는 문자열에 가입하도록 해결할 수 있습니까? 나는 내가 뭘 잘못하고 있는지 알아낼 수 없다.

+0

['str.join'] (https://docs.python.org/2/library/stdtypes.html#str.join)을 사용하지 않는 이유는 무엇입니까? – falsetru

+2

글쎄, 합류가 일어날 곳은 어디입니까? –

답변

7

당신은 this을 할 것입니다 :

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

당신은 (쉼표, ... 공간) 또는 제 1 ''

사이에 단지 더 분리 당신은 그것을 할 수 원하는 구분 기호를 배치 할 수 있습니다 대한 루프하지만/연결이 잘 조절되지 않는 문자열 "또한"비효율적이 될 것 (그러나 물론 그것은 가능) :

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

johnlist = 'john', 'ate', 'a', 'sandwich' 
joinStrings(johnlist) 
0
def joinStrings(stringList): 
    output = "" 
    for gallery in stringList: 
     output += gallery 
     output += " " 
    output = output[:-1] #remove last space 
    return output 

joinStrings('john', 'ate', 'a', 'sandwich') 
관련 문제