Python problem. Collate words


I have the following program:


Write a function that receives two strings as parameters and return   a new string consisting of the first, but with the second string   interleaved between each letter of the first.

For example if the strings are "peace" and "so", then your function should return "psoasozso"

My code:

def intercalar(string_a,string_b):

    r = " "
    i= 0

    while i < l:
        print(string_a[i] + string_b),\

        i = i + 1

    return r


a=raw_input("Ingrese palabara a: ")
b=raw_input("Ingrese palabara b: ")



For the words: a = peace and b = os returns me: pso aso zso

If I use print(string_a[i] + string_b),end = '' , I get an error.

Can someone help me?

asked by FRANCISCO JAVIER VEGAS FERNAND 03.01.2018 в 15:25

3 answers


Try the following:

def intercalar(a, b):
    i = 0
    cadena = ""
    while(i < len(a)):
        # en lugar de estar imprimiendo dentro del bucle
        # vas a guardar en una variable la nueva cadena en la 
        # cual se soluciona el ejercicio
        cadena += a[i] + b
        # cadena toma lo que ya tenga almacenado (+=) y guarda una letra
        # de la cadena a (a[i]) mas la segunda cadena es decir cadena b
        i = i + 1
    return cadena

# recuerda que en python 3 raw_input paso a ser input
a = raw_input("Ingrese palabara a: ") 
b = raw_input("Ingrese palabara b: ")

print(intercalar(a, b))
answered by 03.01.2018 в 15:42

The response of AR4Z is correct and solves your question, but I want to delve into the problems that your code has. Conceptually the idea is correct but you did not get to complete it, let's see what you missed:

  • You define a variable r that is the variable that will return the function, but beyond initializing it with a space, you do nothing else. In principle you should initialize it blank r = "" and then you should be completing it within while in this way: r = r + string_a[i] + string_b .
  • You use a print to print each iteration, but the print is just that, one way to print by console, that in the case. In Python 2x , the print valor, removes the line break but leaves a blank space and the syntax that you comment that is actually print(string_a[i] + string_b,end = '') is valid only in Python 3x

Rescribing your code taking these details into account:

def intercalar(string_a,string_b):

    r = ""
    i= 0

    while i < l:
        r = r + string_a[i] + string_b
        i = i + 1

    return r

With this, now you can do print(intercalar(a, b)) , the print in this case will be of the value returned by the function.

answered by 03.01.2018 в 16:15

And the cryptic functional solution of a single line, which I could not miss and that I leave here for fans of this type of programming (not for the user, who may not be able to accept this type of response):

>>> a = "paz"
>>> b = "so"
>>> "".join("".join(p) for p in zip(a,[b]*len(a)))
answered by 25.10.2018 в 10:34