专业的JAVA编程教程与资源

网站首页 > java教程 正文

Python字符串详解与示例(python字符串方法大全)

temp10 2025-05-08 21:14:29 java教程 2 ℃ 0 评论

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

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

Python字符串详解与示例(python字符串方法大全)

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

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'

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

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

老板点个赞加收藏呗

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表