相关文章推荐
魁梧的大蒜  ·  AttributeError: ...·  1 年前    · 
爱看球的签字笔  ·  String.CompareToIgnore ...·  1 年前    · 
暗恋学妹的投影仪  ·  vector, classe | ...·  2 年前    · 
千年单身的柚子  ·  Electron入门 ...·  2 年前    · 

删除字符串中的空格并输出

可以使用内置函数 strip() replace() 来删除字符串中的空格。

使用 strip()

string = "  This is a string with spaces  "
string = string.strip()
print(string)
# Output: "This is a string with spaces"

使用 replace()

string = "  This is a string with spaces  "
string = string.replace(" ", "")
print(string)
# Output: "Thisisastringwithspaces"

对于需要仅删除字符串开头和结尾的空格,可以使用 lstrip()rstrip()

string = "  This is a string with spaces  "
string = string.lstrip()
print(string)
# Output: "This is a string with spaces  "
string = "  This is a string with spaces  "
string = string.rstrip()
print(string)
# Output: "  This is a string with spaces"