python 字符串 变量
时间: 2025-02-11 18:05:39 浏览: 43
### Python 中字符串和变量的用法
#### 定义字符串变量
在 Python 中,定义一个字符串变量非常简单。只需要给变量赋上双引号或单引号内的字符即可。
```python
message = "这是一个字符串"
```
此语句创建了一个名为 `message` 的字符串变量[^1]。
#### 类型转换
有时需要将不同数据类型相互转换。例如,可利用内置函数 `int()` 或者 `float()` 将表示数值的字符串转成整数或浮点数;而要实现相反操作——即把数字变成字符串,则应该调用 `str()` 方法。
```python
number_str = "123"
integer_value = int(number_str) # 转换成整数
floating_point_value = float(number_str) # 转换成浮点数
numeric_value = 456
string_representation = str(numeric_value) # 数字转化为字符串
```
上述代码展示了如何完成基本的数据类型之间的转变。
#### 变量与字符串拼接
为了组合多个字符串或是连接字符串与其他类型的值(如数字),可以采用加号 (`+`) 来执行简单的串联工作。不过需要注意的是,在这种情况下应当保证参与运算的各项均为字符串形式。如果不是的话,记得先做相应的类型转换处理。
```python
name = "Alice"
age = 30
greeting = name + ", you are now " + str(age) + " years old."
print(greeting)
```
这段脚本会输出 `"Alice, you are now 30 years old."`[^2]。
#### 使用 format() 插入变量到字符串中
除了直接相加之外,还可以借助于 `.format()` 方法更加灵活地向模板化的字符串里嵌套实际的内容。这允许指定位置参数以及命名参数两种方式来填充占位符 `{}`。
```python
template_with_positional_args = "{}, your age is {}.".format(name, age)
template_with_named_args = "{person_name}'s score was {score} out of 100.".format(person_name="Bob", score=87)
print(template_with_positional_args)
print(template_with_named_args)
```
这里分别打印出了带有位置参数和名称参数的结果[^3]。
阅读全文
相关推荐
















