【问题标题】:Replace word in string in Python while keeping formatting在保持格式化的同时在 Python 中替换字符串中的单词
【发布时间】:2015-02-27 01:04:18
【问题描述】:

我有一个发送电子邮件的 python 脚本,但它需要替换两个单词。每当它替换它们时,它都会破坏格式。例如,消息hello how are you my app is [name] and the url is [url] 在使用此脚本运行后发送电子邮件为

hello how are you my app is AppName
 and the app url is www.example.com

目前我正在使用message.replace("[name]", name).replace("[url]", url)

【问题讨论】:

  • 可能是 name 包含一个尾随换行符。试试:message.replace("[name]", name.rstrip())...
  • 你是什么意思“打破格式”,模板行应该是固定宽度还是什么,不清楚。每个替换方法都会做同样的事情,除非你指的是其他东西(例如固定宽度),在这种情况下你将不得不循环并重新调整空格或类似的东西

标签: python string list replace


【解决方案1】:

使用基本的python方法将变量插入字符串

'hello how are you my app is %s and the app url is %s' % (appName, www.example.com)

在艰难地学习 python 中观察本节 :) http://learnpythonthehardway.org/book/ex6.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 2012-08-01
    • 2014-01-08
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多