【问题标题】:Format a string in python [duplicate]在python中格式化字符串[重复]
【发布时间】:2016-11-23 03:26:41
【问题描述】:

我有以下模板,我将其写入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 

如何将我的字符串模板格式化为正确的格式?

【问题讨论】:

    标签: python string


    【解决方案1】:

    在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)
    

    【讨论】:

      猜你喜欢
      • 2015-01-07
      • 1970-01-01
      • 2013-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多