0

I want to remove the start ' and end ' of a string in Python 3, this is how I do it:

new_words = ast.literal_eval(str(words))

but when the content is W/"128d6ff6070c2313a28f27f367f2a412", (BTW: another content works fine) some special throw this error, this code shows error:

malformed node or string on line 1: <ast.BinOp object at 0x1222875b0>

this is the minimal reproduce function like:

if __name__ == '__main__':
try:
    words = 'W/"128d6ff6070c2313a28f27f367f2a412"'
    new_words = ast.literal_eval(str(words))
    print(new_words)
except Exception as e:
    print(e)

why did this happen? what should I do to fix it? I have read this question: ValueError: malformed node or string. And my string was not a json, I also tried to convert the content to str, but still did not fixed it. What is the rubust way to remove the start ' and end ' of a word in Python 3? The desire output is:

W/"128d6ff6070c2313a28f27f367f2a412"

sometimes the word contains ' in the start or end, I need to remove it. This is the real code of project, the rss source etag was dynamic:

    @staticmethod
    def update_last_modified(source, etag: str, last_modified):
        with session_scope() as local_session:
            try:
                new = local_session.query(RssSource).filter(RssSource.id == source.id).first()
                if StringUtils.not_empty(etag):
                    # remove the string start & end "
                    new.etag = ast.literal_eval(str(etag))
                new.last_modified = last_modified
                local_session.commit()
            except SQLAlchemyError as e:
                local_session.rollback()
            except Exception as e:
                logger.error("update session failed", e)
                local_session.rollback()
            finally:
                local_session.close()
Dolphin
  • 29,069
  • 61
  • 260
  • 539

0 Answers0