python将字符串加入列表
时间: 2023-10-03 15:08:12 浏览: 497
可以使用列表的 `append()` 方法将字符串添加到列表中,示例如下:
```python
my_list = [] # 定义一个空列表
my_str = "hello world" # 定义一个字符串
my_list.append(my_str) # 将字符串添加到列表中
print(my_list) # 输出列表
```
输出:
```
['hello world']
```
相关问题
python 将变量加入到字符串中
在 Python 中,有多种方法可以将变量加入到字符串中。以下列举了其中的几种方法:
1. 使用字符串拼接符号 "+"
```python
name = "Alice"
age = 25
print("My name is " + name + " and I am " + str(age) + " years old.")
```
2. 使用字符串格式化
```python
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
```
3. 使用 f-strings
```python
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
```
以上三种方法都可以将变量加入到字符串中,其中 f-strings 是 Python 3.6 及以上版本才支持的一种方法。
python提取字符串中的单词并将其加入列表
可以使用正则表达式来提取字符串中的单词并将其加入列表,示例如下:
```python
import re
string = "This is a sample sentence."
words = re.findall(r'\b\w+\b', string)
print(words)
```
输出结果为:
```
['This', 'is', 'a', 'sample', 'sentence']
```
解释一下正则表达式 `\b\w+\b`,其中 `\b` 表示单词边界,`\w+` 表示匹配一个或多个字符(字母、数字、下划线),所以整个表达式可以匹配一个完整的单词。`re.findall()` 方法可以返回所有匹配的字符串组成的列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)