How do I use the Python range function in this specific case?

Asked

Viewed 128 times

-2

I have a problem and I’m looking for the best way to solve it.

I have a function that inserts in an array 26 positions starting from the letter 'to' down to the last letter of the alphabet which is the letter 'z' : Ex:


import random

def caractere_array():

    caractere = []
    for i in range(26):
        caractere.append(chr(65+i)) 


def novocaractere_array():

novocaractere = [65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65 ]
incluir = random.randrange(0,200)

for i in [chr(65+i)]: 
#valores a colocar o mesmo incluir 
    try:
        novocaractere[novocaractere.index(i)] = incluir 
    except:
        pass

I thought it would do 'to' n times

I’d like to repeat the character 'to' 26 times using the python range resource. Any idea how to do something like this?

  • 1

    If the list should contain only the letter a, why did you do chr(65+i)?

  • Wow this would not do up to n? Example, a, a ... being char(65 till n times)?

  • You know what the function chr ago?

  • The Chr() function returns the character corresponding to the numeric code passed as parameter.

  • Be careful when editing the question. An issue only serves to correct problems present in the question or improve it, never to change it and ask new questions. If you have any doubt that was not addressed in the original question you should create a new one.

1 answer

2


def caractere_array():
    caractere = []
    for i in range(26):
        caractere.append(chr(65+i)) 

You create a list varies, sets a repeat loop that will do i range from 0 to 25, inclusive, added in the list the value chr(65+i).

If the idea is to generate a list only with the letter 'a', it makes no sense to use chr(65+i), which will generate a character based on the value of i: 'a', 'b', etc. If the idea is to have the same value, there is no reason to vary it. In case it would be:

def caractere_array():
    caractere = []
    for i in range(26):
        caractere.append('a') 

But there is also no reason to do this. To generate a list of 26 'a', just do:

caractere = ['a'] * 26

Browser other questions tagged

You are not signed in. Login or sign up in order to post.