Python - Concatenating
<p>I'm going crazy with the following code which should be really easy but doesn't work :/</p>

<pre><code>class Triangulo_String:

    _string = ''
    _iteraciones = 0
    _string_a_repetir = ''

    def __init__(self, string_a_repetir, iteraciones):
        self._string_a_repetir = string_a_repetir
        self._iteraciones = iteraciones

    def concatenar(self):
        for i in range(0, self._iteraciones, 1):
            self._string = self._string_a_repetir + self._string + '\n'
</code></pre>

<p>I'm initializing <code>_iteraciones</code> to <code>3</code> and <code>_string_a_repetir</code> to <code>'*'</code></p>

<p>And the output is just: </p>

<pre><code>***
</code></pre>

<p>When I'm expecting:</p>

<pre><code>*
**
***
</code></pre>

<p>I've debugged it and when doing the concatenating it just concatenates the self._string_a_repetir, not the _string nor the line break.</p>

<p>Such an easy thing is driving me crazy ._.</p>

<p>The relevant bit is in this part:</p>

<pre><code>for i in range(0, self._iteraciones, 1):
    self._string = self._string_a_repetir + self._string + '\n'
</code></pre>

<p>Letâs go through the iterations one by one:</p>

<pre><code># Initially
_string = ''
_string_a_repetir = '*'
_iteraciones = 3

# i = 0
_string = _string_a_repetir + _string  + '\n'
        = '*'               + ''       + '\n'
        = '*\n'

# i = 1
_string = _string_a_repetir + _string  + '\n'
        = '*'               + '*\n'    + '\n'
        = '**\n\n'

# i = 2
_string = _string_a_repetir + _string  + '\n'
        = '*'               + '**\n\n' + '\n'
        = '***\n\n\n'
</code></pre>

<p>As you can see, this is totally expected to happen, since you never repeat that character more than once per line. And you are also incorrectly concatenating the previous string with the new string (placing it in between the current lineâs text and its line break).</p>

<p>What you are looking for is something like this:</p>

<pre><code>for i in range(0, self._iteraciones, 1):
    self._string = self._string + (self._string_a_repetir * (i + 1)) + '\n'
</code></pre>

<p>The <code>string * number</code> works to repeat the <code>string</code> for <code>number</code> times.</p>

<hr>

<p>As a general note, you should not use those class members that way:</p>

<pre><code>class Triangulo_String:
    _string = ''
    _iteraciones = 0
    _string_a_repetir = ''
</code></pre>

<p>This will create those members as <em>class</em> variables, which are shared across all its instances. This is not directly a problem if you never change the class members but it could cause confusion later. You should instead initialize all instance attributes inside the <code>__init__</code>:</p>

<pre><code>class Triangulo_String:
    def __init__(self, string_a_repetir, iteraciones):
        self._string = ''
        self._string_a_repetir = string_a_repetir
        self._iteraciones = iteraciones
</code></pre>

python