25 lines
892 B
Python
25 lines
892 B
Python
|
||
if __name__ == '__main__':
|
||
# 使用strip方法可以删除不要的字符串,默认是删除空格
|
||
s = ' hello world \n'
|
||
print(s.strip())
|
||
|
||
# 同样的,这个方法还有进阶版本,lstrip和rstrip可以从左右开始检测指定符号进行删除
|
||
# 如果左边开头或右边开头没有指定符号,则不会起作用
|
||
s2 = '---hello world==='
|
||
print(s2.lstrip('-'))
|
||
print(s2.rstrip('='))
|
||
print(s2.strip('-='))
|
||
|
||
# 在这个例子中,hello world中间的空格不会被strip系列函数删除,因为这个方法不会管字符串中间的字符
|
||
# 如果需要删除hello world中间的空格,请使用replace方法
|
||
|
||
# 在一个文件中,我们可以这样进行每一行的信息过滤:
|
||
|
||
# with open(file) as f:
|
||
# lines = (line.strip() for line in f)
|
||
# for line in lines:
|
||
# print(line)
|
||
|
||
|