我可以用Python格式化列表中的文本吗?
我有一个50个值的列表,如下所示:我可以用Python格式化列表中的文本吗?,python,list,formatting,Python,List,Formatting,我有一个50个值的列表,如下所示: ['xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx \n', 'xxxxxx\n', ' xxxxxx \n', 'xxxxxx \n', 'xxxxxx\n', ...] 我想将列表打印为列表,但要格式化列表中的文本。我想去掉单词前后的空格(本例中用xxxxxx替换),并使用.title()函数 我尝试过这样做,但我得到了错误: AttributeError: 'list'
['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'
我理解这个错误,但我想知道是否有其他方法可以格式化列表中的文本。您可以使用
[s.strip().title() for s in my_list]
您可以根据需要使用该列表(包括打印)。您可以使用
[s.strip().title() for s in my_list]
您可以随意处理该列表(包括打印)。问题是字符串是不可变的,您必须创建一个新字符串并替换列表中的旧字符串。一个简单的方法是:
a = ['xxxxxx\n', ' xxxxxx \n', 'xxxxxx \n', 'xxxxxx\n', ...]
a = [x.strip().title() for x in a]
问题是字符串是不可变的,您必须创建一个新字符串并替换列表中的旧字符串。一个简单的方法是:
a = ['xxxxxx\n', ' xxxxxx \n', 'xxxxxx \n', 'xxxxxx\n', ...]
a = [x.strip().title() for x in a]
我的小地图解决方案:
my_list=['xxxxxx\n','xxxxxx\n','xxxxxx\n','xxxxxx\n','xxxxxx\n','xxxxxx\n']
#为简洁起见
map(str.title,(map(str.strip,my_list))
我的小地图解决方案:
my_list=['xxxxxx\n','xxxxxx\n','xxxxxx\n','xxxxxx\n','xxxxxx\n','xxxxxx\n']
#为简洁起见
map(str.title,(map(str.strip,my_list)))
进一步阅读:进一步阅读:如果您仍然需要编写外部函数(我真的不认为您在这种情况下会这样做),那么您最好使用map(format_string,from_list,my_list)
。我认为Sven的答案更容易阅读,但如果你无论如何都需要编写一个外部函数(我真的不认为你在这种情况下会这么做),你最好使用map(format\u string\u from\u list,my\u list)
。我认为斯文的答案更容易阅读