S
S
Sam Pie2018-11-07 00:50:46
Python
Sam Pie, 2018-11-07 00:50:46

Why is the function not working in the class?

Why it works:

def clean(text: str):
    return text \
        .replace('?', '') \
        .replace("|", '') \
        .replace('\"', '') \
        .replace('  ', '') \
        .replace(':', '') \
        .replace('\\', '') \
        .replace('/', '') \
        .replace('>', '') \
        .replace('<', '') \
        .replace('"', '') \
        .replace('+', '') \
        .replace('*', '') \
        .replace(' .', '')
...

class ParseText:

...

    def save_text(self):
        part = open('src/text/{}.txt'.format(clean(partName)), 'w', encoding="utf-8")

And this doesn't work:
def clean(text: str):
    strings = ['?', "|", '\"', ]
    result = (text.replace(i, "") for i in strings)
    result = str()
    for i in strings:
        print(i)
        result = text.replace(i, '')
        continue
    return result
...

class ParseText:

...

    def save_text(self):
        part = open('src/text/{}.txt'.format(clean(partName)), 'w', encoding="utf-8")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MechanicZelenyy, 2018-11-07
@MechanicZelenyy

Because strings are immutable, the replace method cannot change the original string (like any other method) and it returns a new string with everything replaced. In the first case, each subsequent call acts on the string returned by the previous one and eventually returns the correct result.
And it’s also unnecessary to write continue at the end of the loop, it will go on anyway. And set the variable to zero using constructions = str()
Example:

In [4]: a = "abc"

In [5]: b = a.replace("a", "1")

In [6]: print(a,b)
abc 1bc

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question