'Defining function with parameters (str,n) that the index value "n" removes the character in that position? [closed]
Write a function that will accept two parameters: a string and an integer n. Return a new string where the character at index n has been removed. If the value of n is invalid, return the original string.
This function will be called into "main" function Beginning python coder here and I am not the best at understanding how functions work.
my code --> enter image description here
Solution 1:[1]
Here you go...
and your code is not correct.
def removeChar(str, pos):
# str[:pos] gives string from index 0 upto pos (excluding pos)
# str[post+1:] gives string from pos + 1 upto end
return str[:pos] + str[pos+1:]
def main():
print(removeChar("Hello", 2))
main()
Solution 2:[2]
To remove any character from a String, we have to create a new string since Strings are immutable in Python (unlike lists).
There are several ways to do so -
- Using Slicing - This is the most common approach.
s = 'ABCDE'
i = 2
s = s[:i] + s[i+1:]
# s[:i] gives the characters in the string from index 0 to i-1 (excludes index i)
# s[i+1:] gives the characters in the string from index i+1 to end
print(s) # This will print ABDE
- Converting to List - We can convert the string to a mutable list of characters. After removing the character at the specified index, we can convert it back to string.
s = 'ABCDE'
i = 2
l = list(s) # Convert to list
del(list[i]) # Deletes the character at index i from the list
s = "".join(l) # Converts the list back to string
print(s) # This will print ABDE
Now, let's discuss about your code :)
def missingChar (str, n):
str = ""
# str is taken as an argument for the function. If it is initialized to "", the purpose of taking it as an input to the function is not served
index = str
value = n
# The above lines are unnecessary
for index in str: # Since, the value of the index at which the character should be removed is already given, a for loop is not needed
index.pop(value) # pop() is a list method... So, it can't be used with strings
return
# Create the main function that will be used throughout the HW
def main():
missingChar("kitten",1) # The function call is perfect :)
# If you want to print the output of the function 'missingChar', store the return value in a variable, and then print it or directly print it by calling the function inside print()
main()
Considering your approach, the following can be done -
def missingChar (s, n):
l = list(s) # Convert to list
l.pop(n) # Use the pop() list method freely :)
s = "".join(l) # Convert the list to string
return s
def main():
result = missingChar("kitten",1)
print(result)
# OR
# print(missingChar("kitten",1))
main()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Shreyasi Mandal |
