Python Data Structure Algorithm Question 30: Delete Unnecessary Characters in Strings

question:

You want to remove unwanted characters, such as whitespace, from the beginning, end, or middle of a text string.

solution:

The strip() method can be used to remove starting or ending characters. lstrip() and rstrip() perform deletion operations from the left and right respectively. By default, these methods strip whitespace characters, but you can specify other characters.

>>> # Whitespace stripping >>> s = ' hello world \n' >>> s.strip()
'hello world'
>>> s.lstrip() 'hello world \n' >>> s.rstrip() ' hello world' >>>
>>> # Character stripping >>> t = '-----hello=====' >>> t.lstrip('-') 'hello====='
>>> t.strip('-=') 'hello'
>>>

These strip() methods are often used when reading and cleaning data for subsequent processing. For example, you can use them to remove spaces, quotes, and perform other tasks.

However, it should be noted that the removal operation will not have any effect on the text in the middle of the string.

>>> s = ' hello world \n' >>> s = s.strip()
>>> s
'hello world'
>>>

If you want to deal with the spaces in between, then you'll need to resort to other techniques. For example, use the replace() method or replace with regular expressions.

>>> s.replace(' ', '') 'helloworld'
>>> import re
>>> re.sub('\s+', ' ', s) 'hello world'
>>>

Often you want to combine string strip operations with other iterative operations, such as reading multiple lines of data from a file. If this is the case, then generator expressions can come in handy.

with open(filename) as f:
lines = (line.strip() for line in f) for line in lines:
print(line)

Here, the expression lines = (line.strip() for line in f) performs data conversion operations. This method is very efficient because it does not require pre-reading all the data into a temporary list. It simply creates a generator and performs a strip operation before returning each row.

For higher order strips, you may want to use the translate() method.

おすすめ

転載: blog.csdn.net/m0_68635815/article/details/135463843