📜  python string trim - Python (1)

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

Python String Trim

Introduction

In Python, you can use the strip() method to remove whitespace (spaces, tabs, and newlines) from the beginning and end of a string. This is commonly referred to as "trimming" a string.

Syntax

The syntax for using strip() is as follows:

string.strip()

Here, string is the string that you want to trim. You need to call the strip() method on the string object.

Example

Consider the following code:

string1 = "   Hello, World!   "
string2 = "This is a sentence.   \n   "
string3 = "\t  This is a tabbed string. \t \n  "
print(string1.strip())
print(string2.strip())
print(string3.strip())

The output of this code will be:

Hello, World!
This is a sentence.
This is a tabbed string.

Here, we have initialized three strings with different types of whitespace characters at the beginning and/or end. We then call the strip() method on each string and print the trimmed version.

Conclusion

In conclusion, the strip() method is a useful tool in Python for removing whitespace from the beginning and end of strings. It can be especially handy when reading in input from users or files, where unexpected whitespace characters may be present.