Python Forum
Use range to add char. to empty string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Use range to add char. to empty string (/thread-17542.html)



Use range to add char. to empty string - johneven - Apr-15-2019

This seems simple enough, but I can't seem to get my head around it.

The problem:
Create an empty string and assign it to the variable lett. Then using range, write code such that when your code is run, lett has 7 b’s ("bbbbbbb").

My attempt:
lett = ' '
for _ in range (7):
     append.lett(b)
print(lett)
I'm pretty sure you can't append to a string, but I'm at a loss for other options. It doesn't seem like we can split lett then rejoin.


RE: Use range to add char. to empty string - scidam - Apr-15-2019

lett = ' ' # This is not an empty string! There is space between quotes.
for _ in range(7):
     append.lett(b) #  You can use `+=`, e.g. lett += 'b'
print(lett)



RE: Use range to add char. to empty string - perfringo - Apr-15-2019

You are right, strings in Python are immutable, so you can't append to it.

Two options come in mind - create new string with every iteration of loop or append to data structure which is mutable and at the end convert to string.

I just pinpoint that your lett is not empty string:

>>> lett = ' '
>>> len(lett)
1
>>> ' ' in lett
True
>>> lett = ''
>>> len(lett)
0



RE: Use range to add char. to empty string - ichabod801 - Apr-15-2019

I would also note that b is not the string 'b', unless somewhere you have done b = 'b'.


RE: Use range to add char. to empty string - scidam - Apr-15-2019

In general, the problem statement

Quote:Then using range, write code such that when your code is run, lett has 7 b’s ("bbbbbbb").

slightly confuses me. A minimal solution would be
lett = ''
range
lett = 'b' * 7
We've used range function and assigned desired result to the lett variable.
Formally, everything is done. No one requires us to use for-loop.


RE: Use range to add char. to empty string - mbharatkumar - Mar-24-2020

lett = ''
for i in range(7):
lett += 'b'