python基础:字符串的相关操作

字符串方法的操作:capitalize、upper、lower、swapcase、title、center、expandtabs、replace等

 

# TODO:字符串是不可变对象, 所以任何操作对原字符串不会有任何影响
str = "python⽜BA"
# 首字母大写
res = str.capitalize()
print(res)

# 转换为大写
res = str.upper()
print(res)

# 转换为小写
res = str.lower()
print(res)

# 大小写互换
res = str.swapcase()
print(res)

# 每个被特殊字符隔开的字⺟⾸字⺟⼤写
# 中⽂也算是特殊字符
# Python⽜Baq
res = res.title()
print(res)

# 居中
# 拉⻓成10, 把原字符串放中间.其余位置补*
str1 = "周杰伦1"
res = str1.center(10, "*")
print(res)

# 更改tab的长度
# 默认⻓度更改为8
str2 = "周杰伦\t欧得洋\t刘若英"
print(str2)
print(str2.expandtabs(10))

# 字符串替换
str3 = "我的昵称为奔奔"
res = str3.replace("奔奔", "benben")
print(res)

res = str3.replace("", "ben")
print(res)

res = str3.replace("", "ben", 1)
print(res)

 

运行结果:

Python⽜ba
PYTHON⽜BA
python⽜ba
PYTHON⽜ba
Python⽜Ba
***周杰伦1***
周杰伦    欧得洋    刘若英
周杰伦       欧得洋       刘若英
我的昵称为benben
我的昵称为benben
我的昵称为ben奔

 

posted @ 2020-06-11 13:21  奔奔-武  阅读(155)  评论(0编辑  收藏  举报