2012-02-21 66 views
0

我有50个值,看起来像这样的列表:我可以使用Python格式化列表中的文本吗?

['xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx \n', 'xxxxxx\n', 
' xxxxxx \n', 'xxxxxx \n', 'xxxxxx\n', ...] 

我想打印的清单作为一个名单,但格式化列表中的文本。我想删除该单词前后的空格(在此示例中用xxxxxx替换)以及使用.title()函数。

我已经试过这样做,但我得到的错误:

AttributeError: 'list' object has no attribute 'strip' 

我的理解是错误的,但我不知道是否有任何其他的方式来格式化文本列表内。

回答

3

您可以使用

[s.strip().title() for s in my_list] 

格式正确的字符串列表,并与任何你想要的(包括打印)该名单做。

+1

延伸阅读:http://docs.python.org/tutorial/ datastructures.html#列表理解 – cheeken 2012-02-21 00:43:17

+0

这是完美的!非常感谢:) – emagdnim 2012-02-21 00:47:22

1

问题是字符串是不可变的,你必须创建一个新的字符串并替换列表中的旧字符串。一个简单的方法是:

a = ['xxxxxx\n', ' xxxxxx \n', 'xxxxxx \n', 'xxxxxx\n', ...] 
a = [x.strip().title() for x in a] 
0
my_list=['xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx \n', 'xxxxxx\n', ' xxxxxx \n', 'xxxxxx \n', 'xxxxxx\n'] 

def format_string_from_list(_str): 
    return _str.strip().title() 

my_new_list=[format_string_from_list(_str) for _str in my_list] 
print my_new_list 

>>> ['Xxxxxx', 'Xxxxxx', 'Xxxxxx', 'Xxxxxx', 'Xxxxxx', 'Xxxxxx', 'Xxxxxx', 'Xxxxxx', 'Xxxxxx'] 
+1

如果你需要编写一个外部函数(我真的不认为你在这种情况下做),但你也可以使用'map(format_string_from_list,my_list)'。我认为斯文的回答更容易阅读 – 2012-02-21 00:49:09

0

我的小映射解决方案:

my_list = ['xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx \n']#缩短为简洁 map(str.title, (map(str.strip, my_list)))

相关问题