add strings by means of a for loop in Python

1

estimates, a query how can I add strings using a for loop in Python? , in my particular case, I want to add consecutive elements of a list and convert them into a single string

 n=int(input("ingrese un numero))

 a[[w,e,r],[t,d,f],[e,h,j]]

 for i in range (n):
     a[1]+...+a[n]

something of that style

    
asked by VICENTE DANIEL PALACIOS 21.05.2017 в 04:13
source

5 answers

2

In this type of operation, using generators is a very efficient solution. With this we avoid the use of any intermediate variable, chain concatenation and the use of comparisons that make the code much more inefficient, besides having to write much less code.

One option is to use itertools.islice() next to a generator that returns the elements from the matrix flattened to do this:

import itertools

n = int(input("largo del string: "))
a = [["w","e","r"],["t","d","f"],["e","h","j"]]
s = ''.join(itertools.islice((j for i in a  for j in i), n))
print(s)

Since in this case the 'slice' on the generator is always 0:n we can do without itertools.islice() and simply do:

n = int(input("largo del string: "))
a = [["w","e","r"],["t","d","f"],["e","h","j"]]

gen = (caracter for lista in a for caracter in lista)
s = ''.join(next(gen) for _ in range(n))

print(s)

Exit examples:

  

length of string: 2
  we

     

length of string: 5
  wertd

     

length of the string: 8
  wertdfeh

     

length of the string: 20
  wertdfehj

If your list is relatively small and your n are going to be generally large with respect to the entry list the conversion to list is more efficient at run time (not in memory usage) than implement generators:

res = ''.join([caracter for lista in a for caracter in lista])[:n]

In this case list compression is used but there are other approaches like the solution proposed by José Hermosilla Rodrigo (see comment below for this answer) using itertools.chain.from_iterable or @Alexis' answer, which are very good in terms of time execution and simplicity of code in this assumption (lists not excessively extensive with n relatively large).

    
answered by 21.05.2017 в 11:12
1

I leave you a way to do it, you had several syntax errors, keep an eye on that.

n = input("largo del string: ")       # recibo el largo del string que quiera

a = [["w","e","r"],["t","d","f"],["e","h","j"]]   # la matriz de caracteres
s = "";                                           # un string vacío para después llenarlo
c = 0;                                            # un contador para restringir el largo del string que se pidió en el input de la variable n

for i in a:                 # ciclo for que tomará el valor de cada elemento de matriz a
    for j in i:             # ciclo for que tomará el valor de cada sub elemento de matriz a  (j contiene las letras )
        if c < n:           # si el contador es menor al largo que pediste
            c += 1          # +1 al contador para la siguiente iteración
            s += j          # j posee cada caracter de la matriz a, entonces lo sumo

print s                     # imprimo el string recién creado en la variable s

I hope I have helped you.

    
answered by 21.05.2017 в 04:56
1

The simplest solution is:

"".join(sum(a,[]))[:n]
    
answered by 21.05.2017 в 21:57
1

Python is so cool that it simplifies the code in the following way:

    lista = ['p', 'y', 't', 'h', 'o', 'n']
resultado = ''.join(lista)
print(resultado)

The variable resultado is formed by a string that is the separator of the elements that is in the list that is passed to the function join as parameter, this code prints python if you modify the code resultado = ' '.join(lista) the result will be python

    
answered by 21.05.2017 в 22:28
1

I will give you two solutions (Pyhon 2,7):

First: The "+" operator allows us to concatenate (join) characters or chains of these. What you have to take care of is that everything you are going to join is a string, because if you try to join a string with an int it will generate an error.

letras  = ["U","n","i","e","n","d","o"] #Letras que uniremos
palabra = ""                            #Variable en la cual crearemos la palabra
for letra in letras:                    #Recorreremos cada elemento del arreglo "letras"
    palabra = palabra + letra           #Concatenaremos cada letra

print palabra                           #Mostraremos la salida por pantalla

Second: The method "join" allows us to join the characters or strings that are in an array. The method allows us to format the union. If you try the following "word=" + ". Join (letters)" the output would be: U + n + i + e + n + d + o.

letras  = ["U","n","i","e","n","d","o"] #Letras que uniremos
palabra = "+".join(letras)              #Uniremos el arreglo gracias al metodo join.
print palabra                           #Mostramos la salida por pantalla

Greetings, I hope I have helped you.

    
answered by 22.05.2017 в 06:13