0

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)
5
Contributors
7
Replies
50
Views
2 Years
Discussion Span
Last Post by ram_10
0

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
0

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.

0

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

Edited by Gribouillis

0

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
0

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

Edited by sneekula

0

Using itertools.repeat()

from itertools import repeat

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

print(generate_n_chars(10, 'z'))

Edited by Gribouillis

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.