Python str.strip() 方法用于去掉字符串首尾的空白(或指定字符)。
语法
s.strip()
s.strip(chars)参数
可选 chars:要去掉的字符集合;省略则去掉空白字符。
返回值
返回去掉首尾指定字符后的新字符串。
示例
print(" hello ".strip()) # hello
print(" hi ".lstrip()) # hi
print(" hi ".rstrip()) # hi
# 去掉指定字符
print("xxxhelloxxx".strip("x")) # hello
# 用户输入清理
name = input("名字: ").strip()
print(f"你好,{name}")输出:
hello
hi
hi
hello
你好,tom注意事项
lstrip 去左、rstrip 去右。strip(chars) 去掉指定的字符集合。读输入建议先 strip 去掉多余空白。