简体   繁体   中英

string manipulation python for removing tags (webscraping)

n =  '\n            \n                \n                \n                    £10.00 (14%)\n                \n            \n            \n        '
for ietms in n:
    n2 = n.replace('\n', '')
    n3 = n2.replace(' ', '')
    n4 = n3.split('(')
    n5 = n4[1].replace(')', '')

f = [n4[0], n5]
print(f)

so i currently have this to remove the \\n tags and spaces from the the n variable but i feel as if there is a way to do this in a better optimied manner and was wondering if anyone could help, thank you.

In Python str has a method called strip() which removes whitespace characters and special characters like \\n and \\r before and after text.

So you could simplify your program to be:

n =  '\n            \n                \n                \n                    £10.00 (14%)\n                \n            \n            \n        '
print(n.strip())

Which would then output: '£10.00 (14%)'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM