网站首页 > 基础教程 正文
1.字符串的创建
可通过直接赋值、构造或转义字符来创建字符串。
# 普通字符串
s = "Hello, World!"
# 多行字符串(使用三引号)
multi_line_str = '''This is
a multi-line
string.'''
# 转义字符(例如换行符、制表符等)
escaped_str = "Hello\nWorld\tPython!"
print(escaped_str)
2.字符串的索引
字符串的索引从 0 开始,负数索引可以从字符串的末尾访问元素。
s = "Hello, World!"
# 正向索引
print(s[0]) # 输出: H
print(s[7]) # 输出: W
# 反向索引
print(s[-1]) # 输出: !
print(s[-6]) # 输出: W
3.字符串的长度
使用 len() 函数可以获取字符串的长度。
s = "Hello, World!"
print(len(s)) # 输出: 13
4.字符串拼接
可以使用 + 或 join() 方法将多个字符串连接起来。
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出: "Hello World"
# 使用 join 方法
words = ["Hello", "World"]
result = " ".join(words)
print(result) # 输出: "Hello World"
5.字符串切片
通过切片可以提取字符串中的一部分。
s = "Hello, World!"
print(s[0:5]) # 输出: "Hello"
print(s[7:]) # 输出: "World!"
print(s[:5]) # 输出: "Hello"
6.查找和替换
可以使用 find() 方法查找子字符串的索引,或者使用 replace() 方法替换子字符串。
s = "Hello, World!"
print(s.find("World")) # 输出: 7
# 替换字符串
new_str = s.replace("World", "Python")
print(new_str) # 输出: "Hello, Python!"
7.字符串格式化
可以使用 f-string、format() 或 % 来格式化字符串。
name = "Alice"
age = 30
# f-string
greeting = f"Hello, {name}! You are {age} years old."
print(greeting) # 输出: "Hello, Alice! You are 30 years old."
# format 方法
greeting = "Hello, {}! You are {} years old.".format(name, age)
print(greeting) # 输出: "Hello, Alice! You are 30 years old."
8. 字符串的大小写转换
s = "Hello, World!"
print(s.upper()) # 输出: "HELLO, WORLD!"
print(s.lower()) # 输出: "hello, world!"
print(s.capitalize()) # 输出: "Hello, world!"
9.去除空白字符
strip() 方法可以去除字符串两端的空白字符(包括空格、制表符等)。
s = " Hello, World! "
print(s.strip()) # 输出: "Hello, World!"
10.检查字符串内容
可以使用 startswith() 和 endswith() 检查字符串是否以特定子串开始或结束。
s = "Hello, World!"
print(s.startswith("Hello")) # 输出: True
print(s.endswith("World!")) # 输出: True
11.分割字符串
使用 split() 方法将字符串按照指定的分隔符分割成多个部分。
s = "apple,banana,cherry"
fruits = s.split(",")
print(fruits) # 输出: ['apple', 'banana', 'cherry']
以上是对字符串进行的一些常见操作,当然python还提供了很多其他函数来处理字符串,有需要欢迎评论区讨论询问哦!
猜你喜欢
- 2025-03-20 Python水仙花数II(字符串分割)(python水仙花数问题)
- 2025-03-20 一文掌握如何在 Python 中删除字符串中的最后一个字符
- 2025-03-20 Python内置函数详解(python 常用内置函数)
- 2025-03-20 Python 中的字符串(python字符串%d)
- 2025-03-20 一文掌握Python中字符串(字符串 python)
- 2025-03-20 Python字符串:你以为你会了?这8个细节让你代码更高效!
- 2025-03-20 从 Python 字符串中删除特殊字符:完整指南
- 2025-03-20 解锁Python字符串处理的10个神技!让你的代码效率翻倍
- 2025-03-20 【php学习笔记】php中str_split()方法使用笔记
- 2025-03-20 从 Python 中的字符串中删除特殊字符
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)