简体   繁体   中英

How can I delete a letter from a string in a list?

I have to solve the following problem: -Write a program that takes a text as an entry and prints the same text without the letter 'r' in it.The teacher said that we have to use a list to put all the words in it and then remove the letter "r" from them. Here is how I started:

 text = input("Enter some text: ")
 l=text.split(" ")
 for i in range(len(l)): #I want to use for to run the elements of the list

I don't know what to do next and what method I should use, I thought maybe the method remove() can be useful,but I don't know how to use it in each item of the list.

Welcome to SO, 👋

Here is my version.

statement = input("Enter some text: ")
listOfWords = statement.split(" ")
for i, word in enumerate(listOfWords):
    if("r" in word.lower()):
        print("found an instance of letter r in the word ({0})".format(word))
        listOfWords[i]=word.replace("r", "")

sentence = " ".join(listOfWords)
print(sentence)

First - it grabs all the words from the input text as a list. Then it iterates over all the words and if there is a "r" , it removes it from the word and updates the list as well. At the every end it generates the sentense back from the list.

Please note - this is ultra verbose code. It does not use Python features like List Comprehension, but it is much easier to understand. I purposefully added debug statements.

Please let me know if this works for you.

Thanks

For the list: str.split() will give a list of each item surrounded with whitespace (You can specify any delimiter you like)

Let's start with an individual list item... We will go with "Rollercoaster".

We can use the in keyword to check if a substring included in a larger string.

text = input("Enter some text: ")
result = ""
for ch in text.lower():
    if ch == 'r':
        continue
    else:
        result += ch
print(result)

Returns

Enter some text: rollercoster
ollecoste

Process finished with exit code 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM