你最終恢復了......你更喜歡這些可能性之一嗎? :
def print_host(host,serv,numb, ch = ('define host {{\n'
' {0:<21}{6}\n'
' {1:<21}{6}\n'
' {2:<21}{6}\n'
' {3:<21}{7}\n'
' {4:<21}{8}\n'
' {5:<21}{9}\n'
'}}\n' )):
f = open(host, 'w')
f.write(ch.format('host_name','alias','display_name',
'address','use','register',
host,
str(socket.gethostbyname(host)),serv,numb))
或
def print_host(host,serv,numb):
tu = ('define host {',
' {:<21}{}'.format('host_name',host),
' {:<21}{}'.format('alias',host),
' {:<21}{}'.format('display_name',host),
' {:<21}{}'.format('address',str(socket.gethostbyname(host))),
' {:<21}{}'.format('use',serv),
' {:<21}{}'.format('register',numb),
'}\n')
f = open(host, 'w')
f.write('\n'.join(tu))
或
def print_host(host,serv,numb):
f = open(host, 'w')
f.writelines(('define host {\n',
' {:<21}{}\n'.format('host_name',host),
' {:<21}{}\n'.format('alias',host),
' {:<21}{}\n'.format('display_name',host),
' {:<21}{}\n'.format('address',str(socket.gethostbyname(host))),
' {:<21}{}\n'.format('use',serv),
' {:<21}{}\n'.format('register',numb),
'}\n'))
或(我喜歡這種簡潔之一)
def print_host(host,serv,numb):
f = open(host, 'w')
f.writelines(('define host {\n',
' host_name {}\n'.format(host),
' alias {}\n'.format(host),
' display_name {}\n'.format(host),
' address {}\n'.format(str(socket.gethostbyname(host))),
' use {}\n'.format(serv),
' register {}\n'.format(numb),
'}\n'))
的socket.gethostbyname將被置於一個嘗試套房裏面以後。 ;) – CarpeNoctem 2011-05-02 01:24:43
您可以直接通過字符串格式化來處理空格填充,而不是對其進行硬編碼。 – 2011-05-02 01:26:24