0

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()
3
  • do you mean cadena += clave + str(cadena_aleatoria(x)) ? Commented Sep 25, 2014 at 20:29
  • 1
    Your questions says "while cadena_inicio is smaller than 256," but your code says "while len(cadena)<256" -- could that be part of the problem? Commented Sep 25, 2014 at 20:33
  • So what exactly is your problem? Commented Sep 25, 2014 at 20:34

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.