Skip to main content
 首页 » 编程设计

python之line.replace 即使是部分键匹配而不是整个键匹配也会用值替换

2025年05月04日8JustinYoung

#!/usr/bin/python 
import socket 
import subprocess 
 
ip=socket.gethostbyname(socket.gethostname()) 
 
reps= {'application.baseUrl': 'application.baseUrl="http://'+ip+':9000"', 
'baseUrl': 'baseUrl="http://'+ip+':9000"' 
} 
 
f = open('/opt/presentation/conf/application.conf','r+') 
lines = f.readlines() 
 
f.seek(0) 
f.truncate() 
 
for line in lines: 
        for key in reps.keys(): 
 
            if key in line: 
                line = line.replace(line, reps[key]) 
        f.write(line+'\n') 
f.close() 

问题:它将 application.baseUrl 替换为 baseUrl="http://'+ip+':9000 而不是 application.baseUrl="http://'+ip+':9000,因为 baseUrl 位于 application.baseUrl 中。

如何仅在匹配整个字符串而不是部分字符串时才替换键

文件名:abc.config

application.baseUrl="http://ip:9000"

baseUrl="http://ip:9000"

远程{

log-received-messages = on 
 
netty.tcp { 
 
  hostname = "ip" 
 
  port = 9999 
 
  send-buffer-size = 512000b 
 
  receive-buffer-size = 512000b 
 
  maximum-frame-size = 512000b 
 
  server-socket-worker-pool { 
 
    pool-size-factor = 4.0 
 
    pool-size-max = 64 
 
  } 
 
  client-socket-worker-pool { 
 
    pool-size-factor = 4.0 
 
    pool-size-max = 64 
 
  } 
 
} 

请您参考如下方法:

因为您想要精确匹配而不是检查:

if key in line: 

你应该这样做:

if key == line[0:len(key)]: 

或者更好,正如 Adam 在下面的评论中所建议的那样:

if line.startswith(key):