📜  python中的strip函数(1)

📅  最后修改于: 2023-12-03 15:19:27.683000             🧑  作者: Mango

Python中的strip函数

简介

strip()是Python中的一个字符串方法,用于去除字符串的首尾空格或指定的字符。

语法
string.strip([char])
参数
  • char (可选): 指定的字符,在去除字符串首尾时将被删除,默认为空格。
返回值
  • 返回去除首尾空格或指定字符后的新字符串。
示例
去除首尾空格
string = "  Hello, World!  "
new_string = string.strip()
print(new_string)  # 输出: "Hello, World!"
去除指定字符
string = "#####Title#####"
new_string = string.strip('#')
print(new_string)  # 输出: "Title"
应用场景

strip() 适用于以下一些常见情况:

清除用户输入中的空白字符
username = input("请输入用户名:")
username = username.strip()
读取文件时去除每行的换行符
with open('file.txt', 'r') as file:
    lines = [line.strip() for line in file]
处理数据时去除额外的空格或字符
data = "   1,  2,   3,  4  "
items = [item.strip() for item in data.split(',')]
注意事项
  • strip() 方法返回的是去除首尾空格或字符后的新字符串,原始字符串并不会改变。
  • 如果需要去除字符串中间的空格或字符,可以使用其他方法,例如 replace()

以上就是strip() 函数的介绍和用法。希望对你有所帮助!