• 技术文章 >Python技术 >Python基础教程

    python-字符串替换

    宋雪维宋雪维2020-12-03 17:40:59原创4837

    原字符串str:“hello word china”
    被替换字符串oldstr:“world”
    新替换的字符串newstr:“hi”
    替换结果:hello hi china

    实现:

    1

    2

    3

    4

    5

    第一种方法:直接调用replace()

     

    def strreplace(str, oldstr, newstr):

     

         return str.replace(oldstr,newstr)

    1

    2

    3

    4

    5

    6

    7

    第二种方法:利用re模块正则

     def strreplace(str, oldstr, newstr):

         #先编译正则

         m=re.compile(oldstr)

    #     #替换字符串中的匹配项

         ret=m.sub(newstr,str)

         return ret

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    第三种方法:实现替换函数

    # 找到替换字符的开始位置

    def getindex(str, key):

        n1 = len(str)

        n2 = len(key)

        i = 0

        j = 0

        while i < n1:

            if str[i] != key[j]:

                i = i + 1

            else:

                # index为开始位置

                index = i

                while j < n2:

                    if str[i] == key[j]:

                        i += 1

                        j += 1

                    else:

                        #如果不相等继续找,替换字符串的下标重新开始,置为0

                        j = 0

                        break

                return index

        return -1

     

    def strreplace(str, oldstr, newstr):

        index = getindex(str, oldstr)

        # print(index)

        step = index + len(oldstr)

        return str[:index] + newstr + str[step:]

    替换结果

    1

    2

    3

    str = strreplace('hello world china', 'world', 'hi')

     

    结果:hello hi china


    专题推荐:python字符串
    上一篇:python:在字符串中查找指定字符的多个索引方法 下一篇:demo:飞机大战游戏 python小项目

    相关文章推荐

    • python正则表达式findall方法如何使用?• python中repr函数是怎么用的?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网