Python怎么去除字符串首尾空格

55次阅读
没有评论

共计 355 个字符,预计需要花费 1 分钟才能阅读完成。

可以使用 strip() 方法来去除字符串首尾的空格。
示例代码如下:

string = "hello world"
new_string = string.strip()
print(new_string)  # 输出结果为 "hello world"

strip() 方法可以去除字符串首尾的空格,并返回一个新的字符串。如果想去除字符串中间的空格,可以使用 replace() 方法将空格替换为空字符串,示例如下:

string = "hello   world"
new_string = string.replace("","")
print(new_string)  # 输出结果为 "helloworld"

另外,如果只想去除字符串开头的空格,可以使用 lstrip() 方法;如果只想去除字符串末尾的空格,可以使用 rstrip() 方法。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-22发表,共计355字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)