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?
Answers:
Try str.strip
:
...
currency_name = item.text
comps.append({
"currency_name": currency_name.strip()
})
...
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)
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?
Try str.strip
:
...
currency_name = item.text
comps.append({
"currency_name": currency_name.strip()
})
...
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)