Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Removing a character from a string using user input

Python:
[URL='https://learn-us-east-1-prod-fleet02-xythos.content.blackboardcdn.com/5b5739b6d55fd/28057265?X-Blackboard-Expiration=1664582400000&X-Blackboard-Signature=xVUzHAWHlD%2F9sPB4sxsPiOF%2Bj8X78hHWIt7YVkTkCgw%3D&X-Blackboard-Client-Id=100076&response-cache-control=private%2C%20max-age%3D21600&response-content-disposition=inline%3B%20filename%2A%3DUTF-8%27%27Lab%25203%25282%2529.pdf&response-content-type=application%2Fpdf&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEKv%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJHMEUCIQCt36VN%2BAy7sRJ3P%2FGvpfdIHgl91V3L7fFgoMt3YFt53AIgS55w34LgReng9JFLwQBiVieiLgJPEbsX%2FuzOnpbDPksqzAQIZBACGgw2MzU1Njc5MjQxODMiDIl84VAEJrXdkVsidyqpBJNC%2BrCKRUd87Ao8OipAIUjWFtBn8eqxpDqj3vK0FhtfJdVzOAYqhBprRTCT3hPoZXjFizkzvylNS3EBUHqmBkEN7pV093or72zv8qxWJQBycsNOefPyE8ZdNACTb7O8ED30YrIosXp69EkfZITEfvaY4Wm6y%2BgSTzmlER2EMwljP1lCPhM%2FSqgzBeKhvv3U0%2Bt%2FkZy4fbvmB%2BGNdefHYZu5pM60j80MeRiSv%2F9ZxVZV6T4U7T%2Fu6ZRzXy1%2B6czDeZ%2Fs9%2BmLrW%2FhvX5zxd7omewMVE%2BUJn09lGlHO1bHTAo7G1zbqiWlOS1ONLqtgnvbEEuFZGczTwPRVv6LnyO1HyT5bvCA1eldfZgrJifGLRDoVRi4TU74friccuXvhsmUGcJbqDMWbIdR1Nz%2BFKlvSw2AUnjQsTsPfT91GpuNOBZDxOqoh5kpUsCEEqGxAlIcIyfk1iul6%2BqUR2%2B0vAPfH%2Fixn1uvEcVoRQs9QRJ%2Bt9g%2Be9VVTiq9ZNUmdyTi9hHzorqPL5g9uunzZ7OawHNYYnEuY7AbC%2BAVsEtweLqGr6NUkdPCw50wYkd9Kgk7FLpjZZGNTibBl0iNdxyn2N2z%2F1Lf0xliV%2BaEUp11oIxJcN1u2simT7HEZiFKRdc%2FKwzp7vCb2xN%2FotowzsIY7e1XK%2BAoi4FpjZbSgq087GMZRN496EillteRTbDSvR7qrtxHkamRrLzjQ1EH%2BQtMKArcQ4rb9GlEGdVhV0wwqvLcmQY6qQEyCVmqVKwVyyykJovsGgc5o7X6r3NTvA8SzX4Cew5v6uv4Px8jv1gc22fR9tpIiPTNIVB%2Bao%2B41K25cyMQcYqj2GUMmkqGElXyDtZ1iS9UrPFbN2sI4CGaAt2EtVvNp%2F%2BjW4v%2BvUkwhNB5kkxylH4ZdTFl5V4JETALK3s9bj113QwXt7XLJzefv%2FHx8oRrseL6ICkWUMz%2BymF4q3YkSccWwRrJwfk9GrVQ&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20220930T180000Z&X-Amz-SignedHeaders=host&X-Amz-Expires=21600&X-Amz-Credential=ASIAZH6WM4PL4TMWCKYZ%2F20220930%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=025c9e96f0c5be619372538622a9f38d3d3ae002ff366a260b5103915ed56c2a']Assignment [/URL]
def deleter():
    string = input("Please enter a string: ")
    final_string = ""
    for i in range(0, len(string)):
        char_remove = input("Please enter character to remove from string (type 'quit' to quit) ") # the character i want to remove
        if(char_remove == "quit"): # if the input is 'break' the code will end
            break
        if(i != char_remove): # I don't understand what this is doing exactly I saw it in a youtube video but it is removing characters which is better than what I had before
            final_string = char_remove + string[i]
        print(final_string)



if __name__ == '__main__':
    deleter()
 
Python:
def deleter():
    string = input("Please enter a string: ")
    char_remove = input("Please enter character to remove from string (type 'quit' to quit) ")  # the character i want to remove
    while(char_remove != "quit"):
        for i in range(len(string)):
            if(string[i] == char_remove):
                string = string[ : i]  +  string[i + 1: ]# string is cake, character to remove is e, index is [0:i] or [cak] + [i + 1: ] or [cak + 1 which is out of the index and therefore nothing: ]
                break

        print(string)
        char_remove = input("Please enter character to remove from string (type 'quit' to quit) ")  # the character i want to remove



if __name__ == '__main__':
[QUOTE]
    deleter()
I fixed it no worries
[/QUOTE]
 
Here is another way using string replace

Python:
# Define a function
def deleter(astring, characters):
    chars = list(characters)  # List of characters to remove from string
    astring = ''.join([word.lower() for word in astring]) # Make all words lowercase
    for char in chars: # Loop through list of characters
        if char in astring: # Look to see if a character is in the string
            astring = astring.replace(char, '') # Match found replace with ''
    return f'\n{astring}\n' # Return the string

while True:
    print('Type exit and press enter to exit program')
    astring = input('Please enter a string:\n>> ')
    if not astring:
        print('You did not enter a string')
        astring = input('Please enter a string:\n>> ')
    elif astring == 'exit':
        print('Goodbye!')
        break
    else:
        characters = input('Please enter characters to remove\n>> ')
        if not characters:
            print('You did not enter any characters to remove')
            characters = input('Please enter characters to search\n>> ')
        elif characters == 'exit':
            print('Goodbye!')
            break
        else:
            print(deleter(astring, characters))

Output:
Code:
Type exit and press enter to exit program
Please enter a string:
>> This is a string also known as text
Please enter characters to remove
>> it

hs s a srng also known as ex

Type exit and press enter to exit program
Please enter a string:
>> exit
Goodbye!
 
Last edited:
One more example using list, list comp, and list.pop()

Python:
def deleter(string, characters): # Define the function
    print(f'String -> {string}') # Print original string
    string = list(string) # Create a list from string
    chars = list(characters) # Create a list of characters
    # List comp to search for and remove characters / uses list pop by index
    [string.pop(i) for char in chars for i, character \
        in enumerate(string) if char.lower() == character.lower()]
    return ''.join(string) # join and return list
print(f"Edited String -> {deleter('Here is a string', 'er')}")

output:
Code:
String -> Here is a string
Edited String -> H is a sting
 
Last edited:
One final example using re

Python:
import re # import re
def deleter(string, characters): # Define the function
    res = [] # Create empty list
    for words in string: # Loop through the string getting words
        # Use regrex to find sub strings in the words and replace / append to empty list
        res.append(re.sub(r'['+characters+']', '', words, flags=re.IGNORECASE))
    return ''.join(res) # join and return new list
print(deleter('Here is a string', 'hi'))

output:
Code:
ere s a strng
 
Last edited:
Here is another way using string replace

Python:
# Define a function
def deleter(astring, characters):
    chars = list(characters)  # List of characters to remove from string
    astring = ''.join([word.lower() for word in astring]) # Make all words lowercase
    for char in chars: # Loop through list of characters
        if char in astring: # Look to see if a character is in the string
            astring = astring.replace(char, '') # Match found replace with ''
    return f'\n{astring}\n' # Return the string

while True:
    print('Type exit and press enter to exit program')
    astring = input('Please enter a string:\n>> ')
    if not astring:
        print('You did not enter a string')
        astring = input('Please enter a string:\n>> ')
    elif astring == 'exit':
        print('Goodbye!')
        break
    else:
        characters = input('Please enter characters to remove\n>> ')
        if not characters:
            print('You did not enter any characters to remove')
            characters = input('Please enter characters to search\n>> ')
        elif characters == 'exit':
            print('Goodbye!')
            break
        else:
            print(deleter(astring, characters))

Output:
Code:
Type exit and press enter to exit program
Please enter a string:
>> This is a string also known as text
Please enter characters to remove
>> it

hs s a srng also known as ex

Type exit and press enter to exit program
Please enter a string:
>> exit
Goodbye!
Why are you using an if statement to check if the char is in the string? Even if the char isn't in the string `.replace` won't raise an error.
 
Last edited:
I don't understand the question. Both examples seem almost the same. Both loop through the chars to get the characters to remove. My example I do test if the characters are in the string. I see that I did not need to puth the chars in a list as it works without out it. As for case sensitive, that's why I put the whole string to lowercase. Sorry I misread the comment.
 
Last edited:

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom