Python字符串详解与示例

liftword1个月前 (03-30)技术文章12

艾瑞巴蒂字符串的干货来了,

字符串是程序中最常见的数据类型之一,用来表示数据文本,下面就来介绍

下字符串的特性,操作和方法,和一些示例来吧道友:

1. 字符串的创建

在python中字符串可以永单引号(' ')双引号(" ")和或三引号(''' '''或""" """)来创建。

# 单引号字符串
str1 = 'Hello, World!'

# 双引号字符串
str2 = "Python Programming"

# 三引号字符串(可以跨多行)
str3 = '''This is a 
multi-line 
string.'''

print(str1)
print(str2)
print(str3)

2. 字符串的基本操作

访问子串串的字符

s = "Python"
print(s[0])  # 输出: 'P' (第一个字符)
print(s[-1]) # 输出: 'n' (最后一个字符)

字符串切片(字符提取可以这么理解)

s = "Programming"
print(s[0:4])   # 输出: 'Prog' (索引0到3)
print(s[3:])    # 输出: 'gramming' (从索引3到最后)
print(s[:6])    # 输出: 'Progra' (从开始到索引5)
print(s[-5:-2]) # 输出: 'mmi' (倒数第5到倒数第3)
print(s[::2])   # 输出: 'Pormig' (每隔一个字符)

字符串连接(+号链接)

s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)  # 输出: 'Hello World'

字符串重复(*号后面加重复次数)

s = "Hi"
print(s * 3)  # 输出: 'HiHiHi'

3. 字符串常用方法

查找方法

s = "Python Programming"

# find() - 返回子字符串的起始索引,找不到返回-1
print(s.find("Pro"))  # 输出: 7
print(s.find("Java")) # 输出: -1

# index() - 类似find(),但找不到会抛出异常
print(s.index("Pro")) # 输出: 7

# count() - 统计子字符串出现次数
print(s.count("m"))   # 输出: 2

修改方法 (大小写,替换)

s = "  hello world  "

# lower()和upper()
print(s.upper())      # 输出: '  HELLO WORLD  '
print(s.lower())      # 输出: '  hello world  '

# strip() - 去除两端空白
print(s.strip())      # 输出: 'hello world'

# replace() - 替换子字符串
print(s.replace("world", "Python"))  # 输出: '  hello Python  '

# split() - 分割字符串
print("apple,banana,orange".split(","))  # 输出: ['apple', 'banana', 'orange']

检查方法

s = "Python123"

# isalpha() - 是否全是字母
print(s.isalpha())    # 输出: False

# isdigit() - 是否全是数字
print("123".isdigit()) # 输出: True

# isalnum() - 是否只包含字母和数字
print(s.isalnum())    # 输出: True

# startswith()和endswith()
print(s.startswith("Py"))  # 输出: True
print(s.endswith("23"))    # 输出: True

4. 字符串格式化 三种格式

% 格式化 (旧式)

name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))

str.format() 方法

name = "Bob"
age = 30
print("My name is {} and I'm {} years old.".format(name, age))
print("My name is {1} and I'm {0} years old.".format(age, name))

f-strings (Python 3.6+)

name = "Charlie"
age = 35
print(f"My name is {name} and I'm {age} years old.")
print(f"Next year I'll be {age + 1} years old.")

5. 字符串的转义字符

print("Line1\nLine2")  # 换行
print("Tab\tseparated")  # 制表符
print("This is a backslash: \\")  # 反斜杠
print("She said, \"Hello!\"")  # 双引号
print('It\'s raining')  # 单引号

6. 字符串不可变性

字符串是不可变的,意味着不能直接修改字符串中的某个字符

s = "hello"
# s[0] = 'H'  # 这会报错

# 正确的方法是创建新字符串
s = 'H' + s[1:]
print(s)  # 输出: 'Hello'

7. 字符串编码

# 编码为字节
s = "你好"
b = s.encode('utf-8')
print(b)  # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd'

# 解码回字符串
s2 = b.decode('utf-8')
print(s2)  # 输出: '你好'

8. 字符串其他有用方法

# join() - 连接序列中的字符串
words = ["Python", "is", "great"]
print(" ".join(words))  # 输出: 'Python is great'

# partition() - 分割字符串为三部分
print("python.is.cool".partition("."))  # 输出: ('python', '.', 'is.cool')

# zfill() - 用零填充字符串
print("42".zfill(5))  # 输出: '00042'

以上为字符串的常用操作,掌握这基本操作你就张了个翅膀!

多练才是王道,初学着几天不看全忘完!

老板点个赞加收藏呗

相关文章

31个必备的python字符串方法,建议收藏

字符串是Python中基本的数据类型,几乎在每个Python程序中都会使用到它。1、Slicingslicing切片,按照一定条件从列表或者元组中取出部分元素(比如特定范围、索引、分割值)s = '...

Python 字符串 replace () 方法实战指南

在Python编程的世界里,字符串操作可谓是基础且关键的一环。而今天要给大家重点介绍的replace()方法,就像是一把神奇的"魔法剪刀",能精准地对字符串进行"剪裁"和"替换",让你的代码更加简洁高...

Python字符串:你以为你会了?这8个细节让你代码更高效!

今天我们来聊聊Python中最「不起眼」却最常用的数据类型——字符串!你以为"hello world"就是全部?其实字符串藏着很多让人直呼「原来如此」的细节!1. 字符串的「铁律」:一旦创建,终身不变...

如何使用 Python 的 f-string 进行字符串格式化

Python 中的字符串格式化曾经有点麻烦。必须在 % 运算符、str.format() 或字符串连接的组合之间进行选择,才能将变量注入字符串中。幸运的是,Python 3.6 引入了 f-strin...

5 个 Python f-字符串技巧

Python 的 f 字符串不仅仅是将变量嵌入字符串的便捷方式——它们是简化代码并提高可读性的强大工具。自 Python 3.6 引入以来,f 字符串因其灵活性和效率迅速成为开发者的最爱。在本文中,我...