Files
Python_CookBook_repo/2.字符串和文本/11.从字符串中去掉不需要的字符.py
2025-09-10 16:12:45 +08:00

25 lines
892 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)