在Python中,`string`指的是字符串(String),它是一种预定义的内置数据类型,用于表示和操作文本数据。字符串是由字符组成的有序集合,可以包含字母、数字、符号和其他特殊字符。在Python中,字符串可以使用单引号(`'`)或双引号(`"`)括起来表示。
字符串的特点:
不可变性:Python中的字符串是不可变的,意味着一旦创建,就不能更改其内容。
Unicode支持:Python 3中的字符串默认是Unicode编码,可以包含世界上几乎所有语言的字符。
字符串的常见操作:
创建:使用单引号或双引号创建字符串,例如 `s = 'hello'` 或 `s = "world"`。
连接:使用加号(`+`)操作符连接字符串,例如 `s1 = 'hello'`, `s2 = 'world'`,则 `s3 = s1 + s2` 得到 `'helloworld'`。
格式化:可以使用多种格式化方法,如f-string(Python 3.6+)或str.format()方法。
示例:
创建字符串
s1 = 'hello'
s2 = "world"
字符串连接
s3 = s1 + s2 结果为 'helloworld'
使用f-string格式化
name = 'Alice'
age = 30
s4 = f'My name is {name} and I am {age} years old.'
使用str.format()格式化
s5 = 'My name is {} and I am {} years old.'.format(name, age)
字符串是Python编程中非常重要的数据类型,在各种应用中广泛使用,如文本处理、用户输入、文件读写等