How to strip a specific word from a string?

后端 未结 5 1095
醉话见心
醉话见心 2020-12-03 04:20

I need to strip a specific word from a string.

But I find python strip method seems can\'t recognize an ordered word. The just strip off any characters passed to the

5条回答
  •  离开以前
    2020-12-03 04:56

    Providing you know the index value of the beginning and end of each word you wish to replace in the character array, and you only wish to replace that particular chunk of data, you could do it like this.

    >>> s = "papa is papa is papa"
    >>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
    >>> print(s)
    papa is mama is papa
    

    Alternatively, if you also wish to retain the original data structure, you could store it in a dictionary.

    >>> bin = {}
    >>> s = "papa is papa is papa"
    >>> bin["0"] = s
    >>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
    >>> print(bin["0"])
    papa is papa is papa
    >>> print(s)
    papa is mama is papa
    

提交回复
热议问题