Stephen Roda
Stephen Roda

Reputation: 899

Can I format the text inside a list in Python?

I have a list of 50 values that looks like this:

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

I would like to print the list as a list, but format the text inside of the list. I would like to strip the whitespace before and after the word (which is replaced with xxxxxx for this example), as well as use the .title() function.

I've tried doing it, but I get the error:

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

I understand that error, but I'm wondering if there's any other way to format the text inside of a list.

Upvotes: 0

Views: 985

Answers (4)

user118861
user118861

Reputation:

My little mapped solution:

my_list = ['xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx\n', 'xxxxxx \n'] # shorted for brevity map(str.title, (map(str.strip, my_list)))

Upvotes: 0

Rusty Rob
Rusty Rob

Reputation: 17173

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']

Upvotes: 0

Zenon
Zenon

Reputation: 1509

The problem is that strings are immutable, you have to create a new string and replace the old one inside the list. An easy way would be:

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

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601679

You can create a list of the properly formatted string using

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

and do with that list whatever you want (including printing).

Upvotes: 3

Related Questions