Python字符串是Python编程语言中的一种数据型,用于存储和处理文本数据,在Python中,字符串是不可变的,这意味着一旦创建了一个字符串,就不能对其进行修改。

python字符串_Pythonpython字符串_Python(图片来源网络,侵删)

以下是一些常用的Python字符串操作:

1、创建字符串

str1 = 'hello'
str2 = "world"
str3 = '''This is a multiline string.'''

2、访问字符串中的字符

str1 = 'hello'
print(str1[0])  # 输出 'h'

3、字符串切片

str1 = 'hello'
print(str1[1:4])  # 输出 'ell'

4、字符串连接

str1 = 'hello'
str2 = 'world'
print(str1 + str2)  # 输出 'helloworld'

5、字符串长度

str1 = 'hello'
print(len(str1))  # 输出 5

6、字符串方法

str1 = 'hello'
print(str1.upper())  # 输出 'HELLO'
print(str1.lower())  # 输出 'hello'
print(str1.startswith('he'))  # 输出 True
print(str1.endswith('lo'))  # 输出 True
print(str1.find('e'))  # 输出 1
print(str1.replace('l', 'r'))  # 输出 'herro'

7、字符串格式化

name = 'Tom'
age = 20
print('My name is %s and I am %d years old.' % (name, age))  # 输出 'My name is Tom and I am 20 years old.'

以上就是Python字符串的一些基本操作,更多高级的字符串操作可以参考Python官方文档。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。