Python教学之字符串操作

简介: Python教学之字符串操作

Python字符串操作主要包括以下几种:

1. 字符串拼接:使用`+`运算符将两个字符串连接在一起。

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  # 输出:Hello World

2. 字符串重复:使用`*`运算符将字符串重复指定次数。

str1 = "Hello"
result = str1 * 3
print(result)  # 输出:HelloHelloHello

3. 字符串切片:使用`[start:end]`语法从字符串中提取子串。其中,`start`表示起始索引(包含),`end`表示结束索引(不包含)。

str1 = "Hello, World!"
result = str1[0:5]
print(result)  # 输出:Hello

4. 字符串长度:使用`len()`函数获取字符串的长度。

str1 = "Hello, World!"
length = len(str1)
print(length)  # 输出:13

5. 字符串替换:使用`replace()`方法将字符串中的某个子串替换为另一个子串。

str1 = "Hello, World!"
result = str1.replace("World", "Python")
print(result)  # 输出:Hello, Python!

6. 字符串分割:使用`split()`方法将字符串按照指定的分隔符分割成一个列表。

str1 = "Hello, World!"
result = str1.split(", ")
print(result)  # 输出:['Hello', 'World!']

7. 字符串大小写转换:使用`upper()`和`lower()`方法将字符串转换为大写或小写。

str1 = "Hello, World!"
upper_str = str1.upper()
lower_str = str1.lower()
print(upper_str)  # 输出:HELLO, WORLD!
print(lower_str)  # 输出:hello, world!

8. 字符串去除空格:使用`strip()`方法去除字符串两端的空格。

str1 = " Hello, World! "
result = str1.strip()
print(result)  # 输出:Hello, World!

 

相关文章
|
2月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
317 100
|
2月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
432 99
|
2月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
2月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
2月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
2月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
3月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
312 0
|
3月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
280 92
|
3月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。

推荐镜像

更多
下一篇
oss云网关配置