Igal
Igal

Reputation: 13

Concatenate strings in Python?

I have a problem with concatenating strings in Python. I need to concatenate the string clave and cadena_aleatoria(x) while cadena_inicio is smaller than 256. This is my script:

import sys
import random

x = random.randint(0,9)
def cadena_aleatoria(x):
    cadena = []
    cadena.append(x)
    while len(cadena)<10:
            x = random.randint(0,9)
            cadena.append(x)
    b = "".join(str(i) for i in cadena)

    print(b, end = "")


def cadena_inicio():
    clave = "5275328525062135755"
    cadena = clave + str(cadena_aleatoria(x))
    while len(cadena)<256:
            cadena = clave + str(cadena_aleatoria(x))               
    print(cadena)
cadena_inicio()

Upvotes: 0

Views: 1280

Answers (2)

ttheb
ttheb

Reputation: 1

You've got a few problems.

First, you're not returning anything from the function cadena_aleatoria(x), so calling it, is returning None and you don't want to add None to your string. So if you want to return b, you should return b.

The other issue is that you're not adding any length to cadena in the while loop. You probably want to do this:

cadena += clave + str(cadena_aleatoria(x))

You're also not returning anything from cadena_inicio() but maybe this is intentional.

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180540

You need to add to cadena not reassign each time through the loop.

You need to also check while len(cadena + str(cadena_aleatoria(x))) as you may go over once you add str(cadena_aleatoria(x))) to cadena inside the while after your check.

while len(cadena + str(cadena_aleatoria(x))) < 256:
      cadena += clave + str(cadena_aleatoria(x))

You also need return(b) if you don't want to add None's to your cadena string

def cadena_aleatoria():
    cadena = []
    cadena.append(x)
    while len(cadena)<10:
            x = random.randint(0,9)
            cadena.append(x)
    b = "".join(str(i) for i in cadena)
    return b

def cadena_inicio():
    clave = "5275328525062135755"
    cadena = ""
    while len(cadena + cadena_aleatoria(x)) < 256:
            cadena += clave + cadena_aleatoria(x)
    print (cadena)

Your first function can be done using a list comprehension :

def cadena_aleatoria():
    return "".join([str(random.randint(0,9)) for x in range(10)])

def cadena_inicio():
    clave = "5275328525062135755"
    cadena = ""
    while len(cadena + cadena_aleatoria()) < 256:
            cadena += clave + cadena_aleatoria()
    print (cadena)

Upvotes: 1

Related Questions