python3 strip 左边字符串
时间: 2023-05-04 16:04:26 浏览: 74
Python3中的strip函数可以用于去除字符串左右两边的空格或指定的字符。当strip函数只传入字符时,会去除左右两边与该字符相同的字符。例如,假设有一个字符串' hello world! ',我们想要去除字符串左边的空格,则可以使用如下代码:
```
string = ' hello world! '
new_string = string.lstrip() # lstrip()表示只删除左边的字符,rstrip()表示只删除右边的字符,strip()表示删除左右两边的字符
print(new_string) # 输出结果为'hello world! '
```
在这个例子中,我们使用lstrip()函数删除字符串左边的空格,并将新字符串存储在new_string变量中。最后,我们可以通过print()函数输出新字符串,结果为'hello world! ',也即是去除了左边的空格。
相关问题
python字符串strip
Python中的字符串strip()方法是用来去除字符串首尾的指定字符(默认为空格)。
例如,假设我们有一个字符串 " Hello, World! ",其中前面有两个空格和后面有两个空格。如果我们想要去除首尾的空格,可以使用strip()方法:
```python
string = " Hello, World! "
new_string = string.strip()
print(new_string)
```
输出结果为:
```
Hello, World!
```
我们也可以指定要去除的字符,例如去除首尾的感叹号:
```python
string = "!!Hello, World!!"
new_string = string.strip("!")
print(new_string)
```
输出结果为:
```
Hello, World
```
strip()方法返回一个新的字符串,原始字符串不会被修改。
python字符串strip用法
Python字符串的strip()方法用于去除字符串两端的空白字符(包括空格、制表符、换行符等)。该方法不会修改原始字符串,而是返回一个新的字符串。
以下是strip()方法的使用示例:
```python
string = " Hello, World! "
new_string = string.strip()
print(new_string) # 输出:Hello, World!
```
在上面的示例中,原始字符串" Hello, World! "两端包含了空格字符。通过调用strip()方法,我们得到了去除空格后的新字符串"Hello, World!"。
需要注意的是,strip()方法只会去除字符串两端的空白字符,而不会去除字符串内部的空白字符。如果想要去除字符串内部的空白字符,可以使用replace()方法或者正则表达式进行替换。