python字符串知识点总结

liftword2周前 (05-30)技术文章5

Python字符串知识点总结

1. 字符串基础

  • 字符串是不可变的序列类型
  • 可以用单引号(')、双引号(")或三引号('''或""")创建
  • 三引号用于多行字符串
s1 = 'hello'
s2 = "world"
s3 = '''多行
字符串'''

2. 字符串操作

2.1 拼接

s = 'hello' + ' ' + 'world'  # 'hello world'

2.2 重复

s = 'hi' * 3  # 'hihihi'

2.3 索引和切片

s = 'Python'
print(s[0])    # 'P' (第一个字符)
print(s[-1])   # 'n' (最后一个字符)
print(s[1:4])  # 'yth' (切片)
print(s[:3])   # 'Pyt' (从开始到索引2)
print(s[3:])   # 'hon' (从索引3到结束)
print(s[::2])  # 'Pto' (步长为2)

3. 字符串方法

3.1 大小写转换

s = 'Hello World'
print(s.lower())      # 'hello world'
print(s.upper())      # 'HELLO WORLD'
print(s.capitalize()) # 'Hello world'
print(s.title())      # 'Hello World'
print(s.swapcase())   # 'hELLO wORLD'

3.2 查找和替换

s = 'hello world'
print(s.find('lo'))        # 3 (返回索引,找不到返回-1)
print(s.index('lo'))       # 3 (类似find,但找不到会报错)
print(s.rfind('l'))        # 9 (从右开始查找)
print(s.replace('l', 'L')) # 'heLLo worLd'

3.3 分割和连接

s = 'a,b,c,d'
print(s.split(','))       # ['a', 'b', 'c', 'd']
print(' '.join(['a', 'b', 'c'])) # 'a b c'
print(s.partition(','))   # ('a', ',', 'b,c,d')

3.4 去除空白

s = '  hello  '
print(s.strip())   # 'hello'
print(s.lstrip())  # 'hello  '
print(s.rstrip())  # '  hello'

3.5 判断方法

s = '123abc'
print(s.isdigit())   # False (是否全数字)
print(s.isalpha())   # False (是否全字母)
print(s.isalnum())   # True (是否字母或数字)
print(s.islower())   # True (是否全小写)
print(s.isupper())   # False (是否全大写)
print(s.isspace())   # False (是否全空白字符)
print(s.startswith('123')) # True
print(s.endswith('abc'))   # True

3.6 格式化

name = 'Alice'
age = 25
# 旧式格式化
print('My name is %s and I am %d years old.' % (name, age))
# format方法
print('My name is {} and I am {} years old.'.format(name, age))
# f-string (Python 3.6+)
print(f'My name is {name} and I am {age} years old.')

4. 字符串编码

  • Python 3中字符串默认是Unicode (utf-8)
  • 编码解码操作:
s = '你好'
b = s.encode('utf-8')  # 编码为bytes
s2 = b.decode('utf-8') # 解码回字符串

5. 原始字符串

  • 以r开头,忽略转义字符
path = r'C:\new\folder'  # 实际字符串是 C:\new\folder

6. 字符串常量

import string
print(string.ascii_letters)  # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(string.digits)         # '0123456789'
print(string.punctuation)    # 所有标点符号
print(string.whitespace)     # 所有空白字符

7. 其他有用方法

s = 'hello'
print(len(s))           # 5 (长度)
print('e' in s)        # True (成员检查)
print(s.count('l'))    # 2 (计数)
print(s.center(10, '-')) # '--hello---' (居中)
print(s.zfill(10))     # '00000hello' (填充0)

8. 字符串与字节串

  • str类型表示Unicode字符串
  • bytes类型表示二进制数据
  • 两者可以互相转换,但需要指定编码方式
text = "你好"
data = text.encode('utf-8')  # str -> bytes
text2 = data.decode('utf-8') # bytes -> str

相关文章

Python字符串是否有包含子字符串的方法

技术背景在Python编程中,经常会遇到判断一个字符串是否包含另一个子字符串的需求。Python提供了多种方法来实现这一功能,不同方法在使用场景和性能上有所差异。实现步骤使用 in操作符in 操作符是...

Python中检查给定的字符串是否包含数字

本文介绍Python中如何检查字符串是否包含数字。如果给定的字符串中包含数字True,否则返回False。Python中检查字符串是否包含数字的一种简单方法是使用isdigit()方法验证字符串中的每...

Python中,什么是字符串?

在Python中,字符串(str)是由一系列字符组成的数据类型,用来表示文本。例如,"Hello, World!" 就是一个字符串。你可以用单引号(')或双引号(")来...

python 入门到脱坑 基本数据类型—字符串string

以下是Python字符串(String)的入门详解,包含基础操作、常用方法和实用技巧,适合初学者快速掌握:一、字符串基础1. 定义字符串# 单引号/双引号 s1 = 'hello' s...

Python中如何查找字符串及快速掌握一些运用

有的时候,我们需要查找一些内容,输入要查找的文字,能够快速反馈出来。1 我们先看看in关键字的使用s = "hello world" if "world" in s:...

失业程序员复习python笔记——字符串

字符串是由独立字符组成的一个序列,通常包含在单引号('')双引号("")或者三引号之中(''' '''或"...