Reputation: 3
I am stuck on a problem for my class. The pic of the problem is down below. I'm trying to convert this string "abcd efgh ijkl" to this "AbCd eFgH IjKl" using ordinal function/values to capitalize even index numbers.
This is what I got so far:
def mock(string):
index = 0
for i in string:
if string.find(i, index) % 2 == 0:
string.replace(i,(chr(ord(i) - 32)))
index = string.find(i) + 1
return string
print(mock("abcd efgh ijkl"))
Any help is appreciated.
Upvotes: 0
Views: 109
Reputation: 4243
use a for loop and a upper the string by index character
def capitalize(string):
result=""
for i in range(len(string)):
if i%2==0:
result+=string[i].upper()
else:
result+=string[i]
return result
string="abcd efgaah ijklaaa"
print(capitalize(string))
output:
AbCd eFgAaH IjKlAaA
Upvotes: -1
Reputation: 1446
All credit to Andrej Kesely for providing a solution, but I just wanted to improve on it slightly. Since you are already iterating over a string, and the .find() method returns an index position, you do not need to keep track of the index! I've tested the code below and it works just as well.
def mock(string):
for i in string:
if i != ' ' and string.find(i) % 2 == 0:
string = string.replace(i, (chr(ord(i) - 32)))
return string
The above returns "AbCd eFgH IjKl"
Upvotes: 1
Reputation: 195438
str.replace
returns string, but you aren't assigning the return value to anything. Also you need to handle spaces correctly (thanks @JacobStrauss for further simplification!)
def mock(string):
for i in string:
if i != ' ' and string.find(i) % 2 == 0:
string = string.replace(i, (chr(ord(i) - 32)))
return string
print(mock("abcd efgh ijkl"))
Prints:
AbCd eFgH IjKl
Upvotes: 2