python进阶,在第一期的基础上做了极大的优化,整体更加美观易懂
六、字符串 (下)
内容较多(超过3000字),分为上下两个篇幅,此篇是下
6.2.2、修改
6.2.2.1、 replace()
replace(): 用其他字符串替换已有字符串
str_1 = "hello world,hello my friend, hello" #
print(str_1.replace("hello", "Hello")) # 用后面一个Hello替换前面一个hello ,默认替换所有
print(str_1.replace("hello", "Hello", 2)) # 只替换2个,如果替换次数超过子串出现次数,将替换所有
# 结果:
>>> Hello world,Hello my friend, Hello
>>> Hello world,Hello my friend, hello
6.2.3、分割
分割->按照指定字符分割字符串
6.2.3.1、split() # 按照指定字符分割字符串,返回一个列表数据类型
str_1 = "hello world,hello my friend, hello"
num1 = str_1.split("hello") # 分割所有hello
print(num1)
# 结果:
>>> ['', ' world,', ' my friend, ', '']
str_1 = "hello world,hello my friend, hello"
num2 = str_1.split("hello", 2) # 只分割前两个
print(num2)
# 结果;
>>> ['', ' world,', ' my friend, hello']
6.2.4、合并->用一个字符或子串合并字符串
6.2.4.1、join()
join: 用一个字符或者子串合并字符串
list1 = ["a1", "b1", "c1"] # 列表,一个中括号里面放多个数据
# 输出: a1...b...c1...
list2 = "...".join(list1)
print(list2)
# 结果
>>> a1...b1...c1
6.3、大小写转换
小大写转换->转换字符串的大小写
a .capitalize() # 将字符串第一个字符转换成大写 (*)打点调用
str_1 = "hello world,hello my friend, hello"
print(str_1.capitalize()) # 该行的首字母大写
# 结果:
>>> Hello world,hello my friend, hello
b .title() # 该句所有单词首字母统统大写
str_1 = "hello world,hello my friend, hello"
print(str_1.title())
# 结果:
>>> Hello World,Hello My Friend, Hello
c .upper() # 全部小写转大写
str_1 = "hello world,hello my friend, hello"
print(str_1.upper())
# 结果:
>>> HELLO WORLD,HELLO MY FRIEND, HELLO
d .lower() # 全部大写转小写
str_1 = "hello world,hello my friend, hello"
print(str_1.lower())
# 结果
>>> hello world,hello my friend, hello
6.4、删除空白字符->删除字符串中的空白字符
str3 = " ab cd "
# .lstrip() # 删除前面(左侧)的空白字符
print(str3.lstrip())
# .rstrip # 删除后面,右侧的空白字符
print(str3.rstrip())
# .strip # 删除两侧空白字符
print(str3.strip())
# 结果
>>> ab cd
>>> ab cd# 后面的空白被删除
>>> ab cd
6.5、字符对齐->使原字符串字符对齐
str4 = "world"
# .ljust() # 填充字符使原字符串左对齐
print(str4.ljust(10, ".")) # 填充字符使原字符串左对齐->一共10个位,空白部分用.填充,默认空格填充
# .rjust() # 填充字符使字符串右对齐
print(str4.rjust(10, "-")) # 字符串右对齐,10个位,不足用-填充
# .center() # 中间对齐
print(str4.center(15, ".")) # 填充字符奇数时候前面的默认多一个后面的少一个
# 结果:
>>> world.....
>>> -----world
>>> .....world.....