I been trying to learn python a month and a half thu my uni course for my cs degree(1st year) so try to go a lil easy, i decided to redo from where i had problems
This is the question being asked '''Given a string (someString) and an int (removeChar), create a new variable (newString) where the char at index removeChar has been removed. Return newString.
Sounds simple but i cant wrap my head around outputting the newstring without the user inputted character
I know to use string slicing but i dont fully see how to use it with taking out the character and making the new string without it.
if i do
somestring = Alex
newstring = somestring[removechar:]
lets say the remove char is 2, the output is ex
however if i do
somestring = Alex
newstring = somestring[:removechar]
I get the output of Al
after that you would think okay so if removechar: is ex and :removechar is al then e is the letter thats changing the whole string.
But if i do [removechar:removechar] then it should take out the one letter but it doesnt nothing is in the output now. So i cant do it like that
I have to use string slicing for this question bc the time we would be doing this we wouldnt be able to use lists, replace, or translate
What am i missing here that you guys all see?
CodePudding user response:
How this works is it gets all character(s) before the letter you want to remove and then because it is a string it adds that with all the character(s) after the letters you want to remove. The reason we add 1 is because if we do not it will include the letter you want to remove.
def remove(removeCharindx, string):
newString = string[:removeCharindx] string[removeCharindx 1:]
return newString
print(remove(1, "Alex"))