How to delete leading and trailing characters from string?

Question:

I have this code

    for item in items:
        currency_name = item.text
        currency_name.split('n')
        comps.append({
            'currency_name': currency_name
        })

    print(comps)

and this is my print(comps)

{'currency_name': 'nn                     Австралійський долар                   n'}, {'currency_name': 'nn                     Азербайджанський манат                   n'},

How else can i delete this n and space

Asked By: makim

||

Answers:

Try str.strip:

...

currency_name = item.text
comps.append({
    "currency_name": currency_name.strip()
})

...
Answered By: Andrej Kesely

Note that currency_name.split('n') this line is redundant – you just throw away the returned list.

That said str.strip() method would do 'currency_name': currency_name.strip()

However, assuming this is part of scrapping and using Beautiful Soup, there is convenient stripped_strings() method

So

comps = []
for item in items:
    comps.append({'currency_name': next(item.stripped_strings())})

print(comps)

or

comps = [{'currency_name': next(item.stripped_strings())} for item in items]
print(comps)
Answered By: buran
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.