欢迎访问宙启技术站
智能推送

如何使用strip()函数删除字符串的开头和结尾的空格?

发布时间:2023-11-24 02:34:51

strip()函数是Python字符串的内置方法,用于删除字符串开头和结尾的空格(包括换行符、制表符等空白字符)。

使用strip()函数可以按以下步骤进行:

步骤1:定义一个字符串变量,存储需要删除开头和结尾空格的文本。例如:

text = "   This is a sample text with leading and trailing spaces.   "

步骤2:调用strip()函数,删除字符串开头和结尾的空格,并将其赋值给一个新的变量。例如:

stripped_text = text.strip()

步骤3:打印输出结果。可以使用print()函数将删除空格后的字符串打印到控制台上。例如:

print(stripped_text)

完整的示例代码如下:

text = "   This is a sample text with leading and trailing spaces.   "
stripped_text = text.strip()
print(stripped_text)

运行上述代码,输出结果如下:

This is a sample text with leading and trailing spaces.

总结:

- strip()函数用于删除字符串开头和结尾的空格。

- strip()函数不会改变原始的字符串,而是返回一个删除空格后的新字符串。

- 删除的空格包括空格字符、制表符、换行符等。

- 使用print()函数可以将删除空格后的字符串输出到控制台上。