如何就地替换 python 中的多个子字符串

How to perform in place replacement of multiple substrings in python

我有一个用户提供的字符串,其中包含一个或多个 IP 地址,我需要为每个 IP 地址添加反向 dns 查找。我的代码目前适用于单个 IP,我希望它能够对字符串中的多个 IP 执行替换。这样做的最佳方法是什么?

import re
import socket

line = "this is my IP address 8.8.8.8 and my mac address is FF:FF:FF:FF:FF:FF.";
print("Before: " + line)
ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', line)
try:
    domain_name = socket.gethostbyaddr(ip[0])[0]
except socket.gaierror:
    domain_name = "No Reverse"
except socket.herror:
    domain_name = "InvalidIP"

ipd = ip[0] + " [" + domain_name + "]"
line = line.replace(ip[0], ipd)
print("After: " + line)

您可以使用 for 循环扩展您的代码。

>>> line = "this is my IP address 8.8.8.8 or 8.8.4.4 and my mac address is FF:FF:FF:FF:FF:FF."
>>> print("Before: " + line)
Before: this is my IP address 8.8.8.8 or 8.8.4.4 and my mac address is FF:FF:FF:FF:FF:FF.
>>> ips = re.findall( r'[0-9]+(?:\.[0-9]+){3}', line)
>>> 
>>> for ip in ips:
...     try:
...         domain_name = socket.gethostbyaddr(ip)[0]
...     except socket.gaierror:
...         domain_name = "No Reverse"
...     except socket.herror:
...         domain_name = "InvalidIP"
...     ipd = ip + " [" + domain_name + "]"
...     line = line.replace(ip, ipd)
... 
>>> print("After: " + line)
After: this is my IP address 8.8.8.8 [dns.google] or 8.8.4.4 [dns.google] and my mac address is FF:FF:FF:FF:FF:FF.

您可以使用 line.split() 拆分字符串 'line' 并列出所有项目。然后遍历列表以在行字符串中查找一个或多个 IP 地址。所有IP地址都可以存储在一个列表中。

line = "this is my IP address 8.8.8.8 and 9.9.9.9 my mac address is FF:FF:FF:FF:FF:FF.";
a =[]
for i in line.split():
  ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', i)
  if len(ip)!=0:
    a.append(ip)
print (a)

当您有一个包含 2 个 IP 地址的字符串时,输出将是:
[['8.8.8.8'], ['9.9.9.9']]