Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以用Python格式化列表中的文本吗?_Python_List_Formatting - Fatal编程技术网

我可以用Python格式化列表中的文本吗?

我可以用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'

我有一个50个值的列表,如下所示:

['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)
。我认为斯文的答案更容易阅读