zoukankan      html  css  js  c++  java
  • 使用Python 字符串 `replace` 遇到的小问题

    使用Python 字符串 replace 遇到的小问题

    场景:需要replace一串字符串中的8个地方,使用8次replace方法。

    报错信息:

    TypeError: expected a string or other character buffer object
    

    我本以为是使用replace过多次导致的某些地方不兼容。比如原本字符串中找到多个需要匹配的项,可是我没给够待替换的项这种情况。code1

    s = s = ['xxx','xx','xxx','xx','33554111720048','xx','xxxx','xxx.cn']
    
    ht = data.replace('0000',s[0]).replace('1111',s[1]).replace('2222',s[2]).replace('3333',s[3]).replace('4444',s[4]).replace('5555',s[5]).replace('6666',s[6]).replace('7777',s[7])
    

    注意到s[4]是个很长的数字,我本以为这种series的type都是object,既没有去管。尝试code2

    ht = dict()
    for i in range(8):
        if i == 0:
            ht[i] = data.replace('l%d%d%d'%(i,i,i),s[i])
        else:
            ht[i] = ht[i-1].replace('l%d%d%d'%(i,i,i),s[i])
    

    这样最后`ht[7]就是我想要的,然而还是一个报错信息。

    解决办法

    (这是数字过长写不进去引起的?)
    code1中的replace("4444",str(s[4]))即可。

  • 相关阅读:
    算法导论之贪心算法
    编程过程中遇到的一些细节
    c++11和c99
    面试总结(YY一面)
    python(17):字典
    python(16):元组
    python(15):练习题
    python(14):列表
    python(13):字符串
    python(12):练习题
  • 原文地址:https://www.cnblogs.com/aubucuo/p/replace1.html
Copyright © 2011-2022 走看看