2016-11-22 127 views
3

字符串我有以下的模板,我正在寫一個config文件:格式蟒蛇

template = """mkdir /root/.ssh \ 
     && chmod go-rwx /root/.ssh \ 
     && apt-get install -y \ 
      gcc \ 
      libssl-dev \ 
      python-pip \ 
      openssh-server \ 
PATH=/usr/local/jdk1.8.0/bin:$PATH 
""" 
with open('config', 'w') as f: 
    f.write(template) 

,我發現了以下格式:

mkdir /root/.ssh   && chmod go-rwx /root/.ssh   && apt-get install -y    gcc    libssl-   dev    python-pip    openssh-server 

代替:

mkdir /root/.ssh \ 
      && chmod go-rwx /root/.ssh \ 
      && apt-get install -y \ 
       gcc \ 
       libssl-dev \ 
       python-pip \ 
       openssh-server \ 
PATH=/usr/local/jdk1.8.0/bin:$PATH 

如何將我的字符串模板格式化爲正確的格式?

回答

8

在Python \是轉義字符,你有\\逃吧:

template = """mkdir /root/.ssh \\ 
     && chmod go-rwx /root/.ssh \\ 
     && apt-get install -y \\ 
      gcc \\ 
      libssl-dev \\ 
      python-pip \\ 
      openssh-server \\ 
PATH=/usr/local/jdk1.8.0/bin:$PATH 
""" 
with open('config', 'w') as f: 
    f.write(template)