欢迎访问宙启技术站
智能推送

Python中的字符串类型和常用操作

发布时间:2024-01-11 19:26:01

在Python中,字符串是一种不可变的序列类型,用于表示文本数据。字符串的创建可以使用单引号、双引号或三引号,下面是字符串类型和常用操作的例子:

1. 创建字符串

s1 = 'Hello, World!'  # 使用单引号创建字符串
s2 = "Python is awesome"  # 使用双引号创建字符串
s3 = """This is a multiline
string"""  # 使用三引号创建多行字符串

2. 字符串连接

s4 = s1 + ' ' + s2  # 使用+操作符连接两个字符串
print(s4)  # 输出:Hello, World! Python is awesome

3. 字符串长度

print(len(s4))  # 输出:27,返回字符串的长度

4. 获取子字符串

print(s4[0])  # 输出:H,获取字符串的      个字符
print(s4[7:12])  # 输出:World,获取字符串的一部分

5. 字符串切割

s5 = "Apple, Banana, Cherry"
fruits = s5.split(', ')  # 切割字符串,返回一个列表
print(fruits)  # 输出:['Apple', 'Banana', 'Cherry']

6. 字符串替换

s6 = s4.replace('World', 'Universe')  # 替换字符串的一部分
print(s6)  # 输出:Hello, Universe! Python is awesome

7. 字符串查找

print(s6.find('Python'))  # 输出:13,返回子字符串的起始索引
print(s6.find('Java'))  # 输出:-1,未找到时返回-1

8. 字符串是否包含子字符串

print('Universe' in s6)  # 输出:True,判断某个子字符串是否存在

9. 字符串大小写转换

print(s6.upper())  # 输出:HELLO, UNIVERSE! PYTHON IS AWESOME
print(s6.lower())  # 输出:hello, universe! python is awesome

10. 字符串去除空格

s7 = '   Hello, World!   '
print(s7.strip())  # 输出:Hello, World!,去除字符串两端的空格
print(s7.lstrip())  # 输出:Hello, World!   ,只去除左侧空格
print(s7.rstrip())  # 输出:   Hello, World! ,只去除右侧空格

11. 格式化字符串

name = 'Alice'
age = 25
s8 = 'My name is {} and I am {} years old'.format(name, age)
print(s8)  # 输出:My name is Alice and I am 25 years old

12. 字符串转换

num = 42
s9 = str(num)  # 将整数转换为字符串
print(s9 + ' is a number')  # 输出:42 is a number

以上是字符串类型和常用操作的一些例子,字符串在Python中非常常用,可用于文本处理、数据处理、用户输入等各种场景。