Python3中的strip()方法可以用于去除字符串前后的空格,它可以根据需要去除字符串中的空格、换行符、制表符等字符。strip()方法没有参数,只能去除字符串前后的空格,如果想要去除字符串中间的空格,可以使用replace()方法。
strip()方法的使用方法如下:
# 去除字符串前后的空格 str = " hello world " str = str.strip() print(str) # 输出:hello world
strip()方法还可以指定要去除字符串中的特定字符,具体使用方法如下:
# 去除字符串前后的特定字符 str = "###hello world###" str = str.strip("#") print(str) # 输出:hello world
strip()方法还可以指定多个要去除的特定字符,具体使用方法如下:
# 去除字符串前后的多个特定字符 str = "###hello world&&&" str = str.strip("#&") print(str) # 输出:hello world
strip()方法还可以指定去除字符串前后的特定字符序列,具体使用方法如下:
# 去除字符串前后的特定字符序列 str = "###hello world###" str = str.strip("#o") print(str) # 输出:hell world
以上就是Python3中strip()方法去除字符串前后的空格的使用方法,strip()方法可以根据需要去除字符串前后的空格、换行符、制表符等字符,极大地方便了字符串处理。