Python Forum
Use range to add char. to empty string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Use range to add char. to empty string
#1
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.
Reply
#2
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)
Reply
#3
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
I would also note that b is not the string 'b', unless somewhere you have done b = 'b'.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
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.
Reply
#6
lett = ''
for i in range(7):
lett += 'b'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with stripping special char and spaces mumstead 7 2,708 Jun-11-2020, 05:44 AM
Last Post: Yoriz
  String index out of range felie04 2 5,479 Aug-17-2018, 11:18 PM
Last Post: felie04
  string index out of range cusick11 9 14,974 Mar-03-2017, 11:45 PM
Last Post: ichabod801
  Invalid syntax: string index out of range darkreaper1959 6 6,096 Jan-22-2017, 06:24 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020