0

I want Python to take a string and iterate through it, printing several variations with an individual letter capitalized. Like this:

Input:

"hello world"

Output:

"Hello world", "hEllo world", "heLlo world", etc.

Here's what I have so far:

string = "hello world".lower()
for x in range(0, len(string)):
    new_string = string[:(x-1)].lower() + string[x].capitalize() + string[(x-1):].lower()
    print(new_string)

However, this code spits out some pretty funky looking strings:

hello worlHd
Ehello world
hLello world
etc.

I suspect my issue has something to do with the way I'm indexing the string, but I'm not sure what to change. Any ideas?

4
  • You've got the indexing wrong: new_string = string[:x].lower() + string[x].upper() + string[x+1:].lower() Commented Jul 24, 2021 at 16:04
  • something like this could work: [print(string[:(x-1)].lower() + string[x-1].capitalize() + string[(x):].lower()) for x in range(1, len(string)+1)] Commented Jul 24, 2021 at 16:08
  • What happened when you tried checking the values of the individual slices? (try using repr so that you can see quotes around the strings, to highlight empty strings,whitespace etc.) Commented Jul 24, 2021 at 16:08
  • I think the wrong code is that in your first loop ,the expression : string[:(x-1)] means from the zero index ( inclusuve) to the LAST index( exclusive) = string[ 0 : -1)] Commented Jul 24, 2021 at 16:11

2 Answers 2

2

Here's a simple change that should make it work with your syntax.

for i in range(len(string)):
    print(string[:i] + string[i].upper() + string[i+1:])

Output:

Hello world
hEllo world
heLlo world
helLo world
hellO world
hello world
hello World
hello wOrld
hello woRld
hello worLd
hello worlD

There are other methods to do this too, but this one is simple to understand.

PS: You can also add .lower() to the left and right sides. It all depends on the inputs you use.

Sign up to request clarification or add additional context in comments.

Comments

1
string = "hello world".lower()
for x in range(0, len(string)):
    new_string = string[:(x)].lower() + string[x].capitalize()  + string[(x+1):].lower()
    print(new_string)

You need to think like index. So if you use string[(:x-1)] it will add the capitalized character twice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.