Home > Blockchain >  How to delete leading and trailing characters from string?
How to delete leading and trailing characters from string?

Time:09-19

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': '\n\n                     Австралійський долар                   \n'}, {'currency_name': '\n\n                     Азербайджанський манат                   \n'},

How else can i delete this \n and space

CodePudding user response:

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)

CodePudding user response:

Try str.strip:

...

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

...
  • Related