天天看点

python 3.7 replace函数的坑

使用replace时必须用

str=str.replace(old,new)

如果用 str.replace(old,new)会不起作用。

注意:若str中没有old变量,也不会报错

应用:

练习题 —— 全局替换程序:

1.写一个脚本,允许用户按以下方式执行时,即可以对指定文件内容进行全局替换

    python your_script.py old_str new_str filename

2.替换完毕后打印替换了多少处内容

# @Time     :2019/6/8 20:57

'''
练习题1 —— 全局替换程序:
1.写一个脚本,允许用户按以下方式执行时,即可以对指定文件内容进行全局替换
    python your_script.py old_str new_str filename
2.替换完毕后打印替换了多少处内容
'''

import os
import sys

my_sys = sys.argv  # 接收输入的参数
if len(my_sys) != 4:
    print("Wrong inputing!")
    os._exit(0)
else:
    print("Replacing....")

old_str = str(my_sys[1])
new_str = str(my_sys[2])
filename = my_sys[3]
new_file = filename + "_new"

count = 0
with open(filename, mode='r', encoding='utf-8') as f:
    data = f.read()
    if old_str in data:
        data = data.split("\n")  # 用\n分割字符串输出为列表

        f_new = open(new_file, mode='w', encoding='utf-8')  # 创建了文本迭代器

        for i in data:
            if old_str in i:
                count += 1
            i = i.replace(old_str, new_str)

            f_new.write(i + "\n")  # 写入文件
        f_new.close()

if count > 0:
    if os.path.exists(filename):
        os.remove(filename)
    os.replace(new_file, filename)
    print("替换成功,替换了{0}处".format(count))
else:
    print("{0}文件中没有{1}".format(filename, old_str))