- 2
How can I Code this using functions,for loop and if statement
Write a function (preLetterCase) that accepts two parameters (a string, and a letter). The function must return the string with all characters before the first instance of the letter converted to lowercase and all other characters converted to uppercase. Hence, if the specified letter is the first character of the string then the entire string will be converted to uppercase. The new string should be returned by the function. here is my attempt: def preLetterCase(Astring, letter): newstring = "" for ch in str(Astring): if ch == letter: newstring += ch else: print(ch,end= "") return newstring.upper() + ch.upper() print(preLetterCase("keep","e"))
12 Answers
+ 4
Minenhle Simphiwe it's working for me.
Input:
potato chip
hit Enter
a
hit Submit
Output:
potATO CHIP
What error message did you get?
+ 2
David Ashton I See My Mistake Now.It Was A Indexing Error.Thank You So Much Instead of [ndx:] Is Typed [:ndx]
+ 1
you doesn't need "for loop and if statement": use 'index' method of string to get index of the letter inside the string, and use it with slicing notation to concatenate lowercased first part with uppercased second part ^^
+ 1
You can write your code with loops and if statements, but visph 's suggestion is much simpler.
s = input()
l = input()
def preLetterCase(s, l):
n = s.index(l)
return(s[:n].lower() + s[n:].upper())
print(preLetterCase(s, l))
https://code.sololearn.com/ccCZ06CUsP82
+ 1
# using your loop logic:
def preLetterCase(Astring,letter):
newstring = ""
up = False # to keep track on when letter was encountered
for ch in Astring:
if ch == letter: up = True
if up: newstring += ch.upper()
else: ch.lower()
return newstring
print(preLetterCase("keep","e"))
# but slicing using index would be much simpler and efficient... and if code coach, input must be taken from user, not hardcoded:
inp_string = input()
inp_letter = input()
print(preLetterCase(inp_string,inp_letter))
# order depends of test expects (swap both inputs)... or even test expect that you doesn't take inputs, but call itself the required function (in wich case you don't write anything else than the function ^^
+ 1
visph Thanks That Worked!..
0
Hi! Please, show us your code attempt! Thx!
0
David Ashton why giving the code while OP did not provide its own attempt???
0
visph I'm naughty. Perhaps OP will show its attempt using for and if...
0
David Ashton your code is not working properly .please re-check it
0
not an indexing mistake: a slicing mistake ;P
- 1
just posted my attempt please assist