Hello,
I'm trying to define a function that takes an integer 'n' and a character and returns a string, 'n' characters long. I'm totally lost and I've nothing. I read in a forum "".join might help. But that too is beyond perceivable for me at this moment. I do have a failed attempt for this seemingly easy task. Please advise. Thanks.

def generate_n_chars(n,a):
    a = ""
    for i in range(n):
    a+= str(n)
Re: returning a string that's 'n' characters long 80 80

Could be as simple as this ...

def generate_n_chars(n, ch):
    return ch * n

# test
ch = 'z'
n = 10
print(generate_n_chars(n, ch))  # result --> zzzzzzzzzz
Re: returning a string that's 'n' characters long 80 80

Hi vegaseat. I was trying not to use the method. I've a list of tasks that I'm trying to figure out and in the process learn Python. So, the task asks me not to use * ! I was trying to figure a for loop for this, but no good.

Re: returning a string that's 'n' characters long 80 80

Here is a recursive solution

def generate_n_chars(n, c):
    if n == 0:
        return ''
    n, r = divmod(n, 2)
    s = generate_n_chars(n, c)
    return s + s + c if r else s + s
Re: returning a string that's 'n' characters long 80 80

A couple of ways.

from __future__ import print_function

def generate_n_chars(n, a):
    for i in range(n):
        print(a, end='')

def generate_n_chars_1(n, a):
    result = ''
    for i in range(n):
        result += a
    return result

Test:

>>> generate_n_chars(7, 'j')
jjjjjjj
>>> print generate_n_chars_1(20, 'z')
zzzzzzzzzzzzzzzzzzzz
Re: returning a string that's 'n' characters long 80 80

You can use a while loop (stops/breaks when n is zero):

def generate_n_chars(n, ch):
    s = ""  # start with an empty string
    while n:
        s += ch  # build up the string s
        n -= 1   # decrement n by 1
    return s

# test
ch = 'z'
n = 7
print(generate_n_chars(n, ch))  # result --> zzzzzzz

To see what's going on use a temporary test print():

def generate_n_chars(n, ch):
    s = ""  # start with an empty string
    while n:
        s += ch  # build up the string s
        n -= 1   # decrement n by 1
        print(n, s)  # temporary test print
    return s

# test
ch = 'z'
n = 7
print(generate_n_chars(n, ch))  # result --> zzzzzzz
Re: returning a string that's 'n' characters long 80 80

Using itertools.repeat()

from itertools import repeat

def generate_n_chars(n, c):
    return ''.join(repeat(c, n))

print(generate_n_chars(10, 'z'))
Re: returning a string that's 'n' characters long 80 80

wow ! thanks everybody :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.