1

my code:

def word_distribution(stringeling):
    for char in "?!.,":
        Satz = stringeling.replace(char,"")
    return Satz

print(word_distribution("Hallo du Peter? Du! und punkt. und komma,"))

output: Hallo du Peter Du! und punkt. und komma

The code does only remove the first "?" Why when i use the for loop without the function it prints me all the word without punctuation. Thanks for help ;)

3
  • 1
    Alright, we need a canonical question for people who assign to the wrong variable in a loop. I swear I've seen a dozen questions like this one recently. Commented Sep 22, 2018 at 10:27
  • I don't think it will remove the question mark, but only the final comma. Strings in python are immutable, each operation on the string will return a new string. Commented Sep 22, 2018 at 10:32
  • Works great know thanks! @Aran-Fey sorry i found similair questions in the search but they all forgett the return statement ;) Commented Sep 22, 2018 at 10:49

3 Answers 3

1

You can try the following :

def word_distribution(stringeling):
    for char in "?!.,":
        stringeling = stringeling.replace(char,"")
    return stringeling.lower()
Sign up to request clarification or add additional context in comments.

Comments

1

you overwrite Satz every time in the loop with the original stringeling. Try:

def word_distribution(stringeling):
    for char in "?!.,":
        stringeling = stringeling.replace(char,"")
    return stringeling


print(word_distribution("Hallo du Peter? Du! und punkt. und komma,"))

Comments

1

IMHO you don't really need a for loop. Since replace does a fixed replacement hence, I used sub from re module to do search and replace using regex. Below is the code

        import re
        def word_distribution(stringeling):
            Satz = re.sub('[?,.!]',"",stringeling,count=0,flags=0)
            return Satz

Output as follows

>>> print(word_distribution("Hallo du Peter? Du! und punkt. und komma,"))
Hallo du Peter Du und punkt und komma

Refer - Read documentation on re.sub here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.