Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change some lowercase letters to uppercase in string

index = [0, 2, 5]
s = "I am like stackoverflow-python"
for i in index:
        s = s[i].upper()
print(s)

IndexError: string index out of range

I understand that in the first iteration the string, s, become just the first character, an uppercase "I" in this particular case. But, I have tried to do it without the "s = " , using swapchcase() instead, but it's not working.

Basically, I'm trying to print the s string with the index letters as uppercase using Python 3.X

like image 227
Hanan N. Avatar asked Nov 21 '11 19:11

Hanan N.


People also ask

How do I convert a lowercase string to uppercase?

The toLowerCase() method converts a string to lower case letters. Note: The toUpperCase() method converts a string to upper case letters.

How do you change a lowercase character to uppercase in Python?

In Python, upper() is a built-in method used for string handling. The upper() method returns the uppercased string from the given string. It converts all lowercase characters to uppercase. If no lowercase characters exist, it returns the original string.


1 Answers

Strings are immutable in Python, so you need to create a new string object. One way to do it:

indices = set([0, 7, 12, 25])
s = "i like stackoverflow and python"
print("".join(c.upper() if i in indices else c for i, c in enumerate(s)))

printing

I like StackOverflow and Python
like image 196
Sven Marnach Avatar answered Oct 13 '22 01:10

Sven Marnach