-1

Lest say I have string like this:

string = "hello world"

I want to have only praticular letter uppercased so if i choose second letter my output should look like this:

hEllo wold

But if i try for example:

string[1].upper()

My output is:

hello world

And not:

hEllo wold

I dont know why...

Major
  • 7
  • 4
  • 1
    Strings are immutable, `string[1].upper()` creates a new single character uppercased string. You could do what you want with `"".join(c.upper() if c in "eo" else c for c in string)`. – Tim Sep 23 '19 at 10:41
  • What do you mean by "my output"? `string[1].upper()` returns `'E'`. – Stop harming Monica Sep 23 '19 at 10:46

3 Answers3

4

This line:

string[1].upper()

Isn't doing what you think. Sure, it uppercases the value in string[1], but it returns a new string with the result! - because in Python strings are immutable. Now, you'd be tempted to think that this would fix it:

string[1] = string[1].upper()

... But no, this will fail because once again - strings are immutable. You have no choice but to create a new string, with some logic to tell which positions you want to uppercase. For example, to uppercase the value at index = 1:

''.join(c.upper() if i == 1 else c for i, c in enumerate(string))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

To capitalize only one letter of a string you have to capitalize the part of the string starting from the nth position, and assign it back to the variable:

string = string[:n] + string[n:].capitalize()
Nico Griffioen
  • 5,143
  • 2
  • 27
  • 36
0

In Python Strings are not Modifiable hence the operation that you specified would not work.

In order to make this work,you can convert the string to a list and then convert a particular character to uppercase and then join the result back into a string.

sample_str="hello world"

sample_list=list(sample_str)                                           

sample_list[2]=sample_list[2].upper()

print(''.join(str(i) for i in sample_list))
Dhruv Marwha
  • 1,064
  • 2
  • 14
  • 26