Py学习  »  buran  »  全部回复
回复总数  4
3 年前
回复了 buran 创建的主题 » 自动删除前导u'…'在Python字符串中

使用2to3工具 unicode 修理工应该这么做。

unicode

Renames unicode to str.

带样品的试运行 spam.py 文件

eggs = u'foo'

在壳牌:

$ 2to3 --fix unicode spam.py

输出

root: Generating grammar tables from /usr/lib/python2.7/lib2to3/PatternGrammar.txt
RefactoringTool: Refactored spam.py
--- spam.py     (original)
+++ spam.py     (refactored)
@@ -1 +1 @@
-eggs = u'foo'
+eggs = 'foo'
RefactoringTool: Files that need to be modified:
RefactoringTool: spam.py

编辑:注意,您可以只运行一个修复程序,如上图所示(在干运行中),它将仅应用相应的更改。

打印日期时间列表。日期对象,您看到的是列表元素的表示形式。不要打印整个列表,而是从列表元素构造一个str:

import datetime
spam = [datetime.date(2021, 12, 7), datetime.date(2021, 12, 8)]
print(spam)
print(', '.join(map(str, spam)))
print(', '.join(str(item) for item in spam))
print(', '.join(item.strftime('%d.%m.%Y') for item in spam))

输出

[datetime.date(2021, 12, 7), datetime.date(2021, 12, 8)]
2021-12-07, 2021-12-08
2021-12-07, 2021-12-08
07.12.2021, 08.12.2021

或者遍历列表,逐个打印元素。

3 年前
回复了 buran 创建的主题 » 从与条件python匹配的列表创建字典
from itertools import chain

main = ['dayn is the one', 'styn is a main', 'tyrn is the third main']
lst2 = ['dayz', 'stzn', 'tyrm']
lst3 = ['styzerwe', 'tyrmadsf', 'dayttt']
lst4 = ['dayl', 'styyzt', 'tyrl']

def create_dict(main, match=3, *rest):
    result = {item[:match]:[item, []] for item in main}
    result['unmatched'] = ['unmatched', []]
    for item in chain(*rest):
        (result.get(item[:match]) or result['unmatched'])[1].append(item)
    return dict(result.values())

result = create_dict(main, 3, lst2, lst3, lst4)
print(result)

输出:

{'dayn is the one': ['dayz', 'dayttt', 'dayl'], 
 'styn is a main': ['styzerwe', 'styyzt'], 
 'tyrn is the third main': ['tyrm', 'tyrmadsf', 'tyrl'], 
 'unmatched': ['stzn']}
6 年前
回复了 buran 创建的主题 » 用python格式化html

你可以使用一些 template engine that mix logic into template

实例与 jinja2 :

  1. 安装与 pip install jinja2

2那么代码是:

html_text = """<html>
<head>...</head>
<body>
    <table width="100%" height="100%" border="5px">
        {% for title in titles %}
        <tr>
            <td>{{title}}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>"""

from jinja2 import Template
titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
my_templ = Template(html_text)
with open('temp.html', 'w') as f:
    f.write(my_templ.render(titles=titles))

注意,处理可变长度的列表是灵活的。 模板引擎在web框架中使用。