Python总结,字符串的常用操作

简介: Python总结,字符串的常用操作

字符串的查询操作


1675244737100.jpg查询字符串使用index在查询不到的情况下,会抛出异常,中断程序,除非使用其他方法忽略错误。如果使用find在没有查询到的情况下返回-1

string1 = "wish day day up"
#元素位置   0123456789
print(string1.find("day"))
print(string1.rfind("day"))
print(string1.find("z"))

输出:

5
9


字符串的大小写转换操作


1675244790470.jpg

字符串的格式对齐操作


1675244796449.jpg


string1 = "wish day day up"
print(string1.center(21,"*")) #长度21,居中,使用*号填充
print(string1.center(5,"*")) # 长度5,小于目前的长度,将输出原字符

输出:

***wish day day up***
wish day day up
• 1
• 2


字符串的分割操作

1675244833026.jpg

string1 = "wish day day up"
print(string1.split()) #默认以空格进行分割
string2 = "hello|python"
print(string2.split(sep="|")) # 通过|符号分割
string3 = "hello|world|python"
print(string3.split(sep="|",maxsplit=1)) # 最大分一次

输出:

['wish', 'day', 'day', 'up']
['hello', 'python']
['hello', 'world|python']
• 1
• 2
• 3


判断字符串组成内容


1675244851282.jpg


字符串的替换


1675244866492.jpg


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

推荐镜像

更多