Replacing Odd and Even-indexed characters in a string in Python -
can me python string? how can replace , odd-indexed letters in strings? i'd replace odd-indexed characters uppercased letters , even-indexed characters lowercased ones.
x=input("enter string: ") how can modify inputted string?
this sounds little "do homework me" post, i'll out, need training myself.
you can du braking down problem. (as quite new python syntax, i'm gonna assume user has given input string x)
- make loop, or otherwise iterate through characters of string
- make sure have index number each character, increments each one
- check if number even, using modulus of 2 (
%2). returns remainder of number when divided 2. in case of numbers, 0. - if
%2 == 0set letter lower case, else set letter upper case. - append letter new string, defined before loop. cannot directly alter single character in string, because immutable. means cannot change string itself, can assign new string variable.
- done. print , see if worked.
code:
x = "semi long string random casing" result_string = "" index = 0; c in x: if(index%2 == 0): result_string += c.lower() else: result_string += c.upper() index+=1 print(result_string)
Comments
Post a Comment