I started working with python just some days ago and are stuck with a task from codewars. The task can be paraphrased like this:
Write a function that converts strings so that the first letter of each word is capitalized.
In short: I want to solve this task using the strategy so that in the string, each letter that suceeds a blank space is capitalized. However, my approach does not work.
Now my approach looks like this:
def to_jaden_case(string): #defining the function. (string) should be returned with the beginning of each word capitalized.
for x in string:
if x[-1] == " ": #I mean to say: if what comes before the element x is a blankspace, then:
x.upper() #Converting x to capital case using the .upper method.
return(string) #Returning the final string.
If I run this code, it does not return an error, it simply does nothing to achieve the task of modifying the string in the desired way.
Please elaborate on the mistakes in my approach and help me modify it to work! Also, showing and explaining (keeping in mind that I am an absolute beginner) an efficient way to solve the task would be great!
So a few things came to mind when looking at your code.
When you defined your loop you stated
for x in string.This means that every instance of
xis going to be a character from your string. This means thatx[-1]isn't helpful as x is not an array, but a single character.Also, when you use
x.upper()you get the uppercase value ofxbut this is 'lost' as you haven't assigned it to a variable.Additionally you'd want to think about the first character of your sentence, as this does not have a space preceeding it! You could use an
orstatement in yourifstatement to check if this is true.Taking your idea further you could look to loop through each character of your string using a variable such as
iwhich means you can look at the current and previous character easily usingstring[i]andstring[i-1]respectively.You cannot directly change characters of a string (i.e.
string[i] = string[i].upper()is not allowed. To work around this you could create a blank string at the start of your function and then append each character to this new string, either the Upper case or original.The following code would work based on your idea:
A much more effient way around this is to split the string using
string.split()and then capitalise each word usingcapitalize()You can then re-join them together with spaces using
join()I have found a really useful link here that has even more ways of solving this type of problem - well worth a read! https://www.scaler.com/topics/replace-a-character-in-a-string-python/