python:从主机字符串中剥离最后一个句点

Sim*_*eth 6 python regex replace

我很难搞清楚如何从主机名中剥离最后一段时间......

电流输出:

  • domain.com.
  • suddomain.com.
  • domain.com.
  • subdomain.subdomain.com.
  • subdomain.com.

期望的输出:

  • domain.com
  • subdomain.com
  • domain.com
  • subdomain.subdomain.com

尝试1:

print string[:-1]  #it works on some lines but not all
Run Code Online (Sandbox Code Playgroud)

尝试2:

 str = string.split('.')
 subd = '.'.join(str[0:-1])
 print subd    # does not work at all 
Run Code Online (Sandbox Code Playgroud)

码:

global DOMAINS

if len(DOMAINS) >= 1:
  for domain in DOMAINS:
    cmd = "dig @adonis.dc1.domain.com axfr %s |grep NS |awk '{print $1}'|sort -u |grep -v '^%s.$'" % (domain,domain)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,   shell=True)
    string = p.stdout.read()
    string = string.strip().replace(' ','')
    if string:
      print string
Run Code Online (Sandbox Code Playgroud)

ise*_*dev 16

你这样做:

hostname.rstrip('.')
Run Code Online (Sandbox Code Playgroud)

其中hostname是包含域名的字符串.

>>> 'domain.com'.rstrip('.')
'domain.com'
>>> 'domain.com.'.rstrip('.')
'domain.com'
Run Code Online (Sandbox Code Playgroud)