2025-09-10:仓库迁移
This commit is contained in:
24
2.字符串和文本/11.从字符串中去掉不需要的字符.py
Normal file
24
2.字符串和文本/11.从字符串中去掉不需要的字符.py
Normal file
@@ -0,0 +1,24 @@
|
||||
|
||||
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)
|
||||
|
||||
|
Reference in New Issue
Block a user