p ython中字符串通过空格遍历
时间: 2023-07-31 09:04:08 浏览: 47
在 Python 中,可以通过字符串的 `split()` 方法将其按空格进行分割,得到一个由各个单词组成的列表。例如:
```python
s = "Hello world! This is a string."
words = s.split()
print(words)
```
输出:
```
['Hello', 'world!', 'This', 'is', 'a', 'string.']
```
其中,`split()` 方法默认使用空格作为分隔符,如果要使用其他字符作为分隔符,可以在括号中传入该字符作为参数。例如,将字符串按逗号分隔:
```python
s = "apple, banana, orange, mango"
fruits = s.split(", ")
print(fruits)
```
输出:
```
['apple', 'banana', 'orange', 'mango']
```
相关问题
p ython删除字符串中重复字符
你可以使用 Python 中的集合(set)来删除字符串中的重复字符。具体代码如下:
```python
s = "hello world"
s = ''.join(set(s))
print(s)
```
运行结果为:
```
drh weol
```
解释:
- `set(s)` 将字符串 `s` 转换为一个集合,集合中的元素就是字符串中的所有字符,且不包含重复元素。
- `join()` 方法可以将集合转换为字符串,括号中的参数为分隔符,因为我们不需要分隔符,所以传入一个空字符串。
- 最后输出结果即可。
p ython字符串去除空格
在 Python 中,可以使用字符串的 `strip()` 方法去除字符串的头部和尾部的空格。例如,将字符串 `" hello world "` 去除空格可以这样写:
```python
s = " hello world "
s = s.strip()
print(s) # 输出:"hello world"
```
如果只想去除字符串头部的空格,可以使用 `lstrip()` 方法,如果只想去除字符串尾部的空格,可以使用 `rstrip()` 方法。