python中strip()用法
时间: 2023-09-25 18:13:58 浏览: 79
Python中的line.strip()是一个字符串方法,用于去除字符串开头和结尾的空格和换行符。它可以用于读取文件时去除每行的空格和换行符,或者用于处理用户输入时去除输入字符串的空格和换行符。例如:
```
line = " hello world\n"
stripped_line = line.strip()
print(stripped_line) # 输出 "hello world"
```
在这个例子中,line.strip()方法去除了字符串line开头和结尾的空格和换行符,返回了一个新的字符串"hello world",并将其赋值给了变量stripped_line。
相关问题
python中strip用法
在 Python 中,strip() 是一个字符串方法,用于删除字符串开头和结尾的特定字符(默认为空格)。
strip() 的语法如下:
```
string.strip([chars])
```
其中,chars 参数是可选的,用于指定要删除的字符集合。如果不指定 chars 参数,则默认删除字符串开头和结尾的空格符。
下面是一些示例:
```
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.strip(" !")) # "Hello, World"
print(text.strip("H! ")) # "ello, World"
```
第一个示例中,strip() 方法删除了字符串开头和结尾的空格符。
第二个示例中,strip() 方法指定了要删除的字符集合为空格和感叹号,因此删除了字符串开头和结尾的空格和感叹号。
第三个示例中,strip() 方法指定了要删除的字符集合为大写字母 H、感叹号和空格,因此删除了字符串开头和结尾的大写字母 H、感叹号和空格。
Python中strip用法
strip()是Python字符串中的一个方法,用于去除字符串开头和结尾的空格或指定字符。它的用法如下:
1. 去除字符串开头和结尾的空格
```
string = " Hello World "
new_string = string.strip()
print(new_string) # "Hello World"
```
2. 去除字符串开头和结尾的指定字符
```
string = "123Hello World321"
new_string = string.strip("123")
print(new_string) # "Hello World"
```
3. 去除字符串开头的指定字符
```
string = "123Hello World321"
new_string = string.lstrip("123")
print(new_string) # "Hello World321"
```
4. 去除字符串结尾的指定字符
```
string = "123Hello World321"
new_string = string.rstrip("321")
print(new_string) # "123Hello World"
```
注意:strip()方法不会改变原始字符串,而是返回一个新的字符串。如果需要修改原始字符串,可以使用赋值语句。