The method of removing spaces at both ends of the string in Python!

  In Python programming, strings are one of the commonly used data types, and we often encounter situations where strings contain spaces. For processing such strings, we can use Python's built-in strip() function to remove spaces at both ends of the string. The following are the details:

  Syntax: The strip() function is a method of the Python string object, which can be used to remove spaces at both ends of the string.

  str.strip([char])

  Among them, str represents the string object to be processed, and char (optional) represents the character to be removed.

  Sample code:

  # Example 1: Remove spaces at both ends of the string

  str1 = " Hello, World! "

  str2 = str1.strip()

  print("String before processing:", str1)

  print("Processed string:", str2)

  # Example 2: Remove specific characters

  str3 = "||||Hello, World!||||"

  str4 = str3.strip('|')

  print("String before processing:", str3)

  print("Processed string:", str4)

  operation result:

  String before processing: Hello, World!

  Processed String: Hello, World!

  String before processing: ||||Hello, World!||||

  Processed String: Hello, World!

  From the sample code above, we can see how to use the strip() function. When no parameters are passed in, the strip() function will remove spaces at both ends of the string by default. When the specified characters are passed in, the strip() function will remove these specified characters that appear at both ends of the string.

  It should be noted that the strip() function does not modify the original string, but returns a new string. Therefore, we need to assign the return value to another variable to hold the processed result.

  In addition, we can also use the lstrip() function and the rstrip() function to remove the spaces at the left and right ends of the string respectively. The usage is similar to the strip() function. For details, please refer to the following sample code:

  # Example 3: Remove spaces at the left end of the string

  str5 = " Hello, World! "

  str6 = str5.lstrip()

  print("String before processing:", str5)

  print("Processed string:", str6)

  # Example 4: Remove spaces at the right end of the string

  str7 = " Hello, World! "

  str8 = str7.rstrip()

  print("String before processing:", str7)

  print("Processed string:", str8)

  operation result:

  String before processing: Hello, World!

  Processed String: Hello, World!

  String before processing: Hello, World!

  Processed String: Hello, World!

Guess you like

Origin blog.csdn.net/oldboyedu1/article/details/132342221