在列表中的项目中添加空格(Python) [英] Adding spaces to items in list (Python)

查看:952
本文介绍了在列表中的项目中添加空格(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python新手,我需要一些简单问题的帮助.

I'm a Python noob and I need some help for a simple problem.

我需要做的是创建一个包含3个项目的列表,并在每个项目之前和之后添加空格.

What I need to do is create a list with 3 items and add spaces before and after every item.

例如:l1 = ['a', 'bb', 'c']
应该转换为:[' a ',' bb ',' c ']

For example: l1 = ['a', 'bb', 'c']
should be transformed into: [' a ',' bb ',' c ']

我试图写这样的东西:

lst = ['a', 'bb', 'c']
for a in lst:
    print '  a  '

...对于其他元素,依此类推,但出现语法错误. 有人可以建议我这样做的可行方法吗?谢谢.

...and so on for the other elements, but I get a syntax error. Can anyone suggest me a working way to do this? Thanks.

推荐答案

与往常一样,使用这对每个元素应用了字符串格式化操作,并添加了空格.如果您使用的是python 2.7或更高版本,则甚至可以在替换字段(花括号)中省略0.

This applies a string formatting operation to each element, adding the spaces. If you use python 2.7 or later, you can even omit the 0 in the replacement field (the curly braces).

这篇关于在列表中的项目中添加空格(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆