Python字符串基础知识 (三)

版权声明:版权归本人,仅供大家参考 https://blog.csdn.net/Dream____Fly/article/details/84448983

21.向左右格式化打印

S="HHH"
print(S.ljust(6,"+"))
print(S.rjust(6,"+"))
	输出结果:HHH+++
		 +++HHH

22.大写变小写,小写变大写

S="HHH"
print(S.lower())
S="hhh"
print(S.upper())
	输出结果:hhh
		 HHH

23.去掉左边空格和回车,去掉右边空格和回车,去掉两端全部空格和回车

S="\nHHH"
print("1YYY"+S)
print("1YYY"+S.lstrip())
S="HHH\n"
print(S+"2YYY")
print(S.rstrip()+"2YYY")
S="\nHHH\t"
print(S.strip()+"3AAA")
	输出结果:1YYY
		 HHH
		 1YYYHHH
		 HHH
		 2YYY
		 HHH2YYY
		 HHH3AAA

24.自定义格式化(形成对照表),两字符串长度必须一致

p=str.maketrans("1234567","abcdefg")
print("5372".translate(p))
	输出结果:ecgb

25.字符串替换

s="bubu"
print(s.replace("b","B",3))
	输出结果:BuBu

26.从右向左查找

s="AHHH"
print(s.rfind("H"))
	输出结果:3

27.字符串分割

s="bcudsncusiabjdf"
l=s.split("s")
l.append("hao")
print(l)
print(" ".join(l))

s=s.replace("s"," ")+" hao"
print(s)
	输出结果:['bcud', 'ncu', 'iabjdf', 'hao']
		 bcud ncu iabjdf hao
		 bcud ncu iabjdf hao

28.将字符串中的大小写互换

s="HUbfjds"
print(s.swapcase())
	输出结果:huBFJDS

29.将字符串中的每一个单词首字母变大写

s="feng oo pbce"
print(s.title())
	输出结果:Feng Oo Pbce

30.格式化操作

s="10"
print(s.zfill(8))
	输出结果:00000010

猜你喜欢

转载自blog.csdn.net/Dream____Fly/article/details/84448983