1.字符串的修饰
center让字符串在指定的长度居中,如果不能居中左短右长,可以指定填充内容,默认以空格填充ljust让字符串在指定的长度左齐,可以指定填充内容,默认以空格填充rjust让字符串在指定的长度右齐,可以指定填充内容,默认以空格填充zfill将字符串填充到指定长度,不足地方用0从左开始补充format按照顺序,将后面的从参数传递给前面的大括号strip默认去除两边的空格,去除内容可以指定rstrip默认去除右边的空格,去除内容可以指定lstrip默认去除左边的空格,去除内容可以指定练习:center():居中
test='hello' print(test.center(9)) 运行结果: hello #这个hello居中,默认由空格填充。效果不明显,我们填充字符来查看 test='hello' print(test.center(9,'x')) 运行结果:xxhelloxx练习:ljust():左对齐
test='hello' print(test.ljust(9,'x')) 运行结果:helloxxxx练习:rjust():右对齐
test='hello' print(test.rjust(9,'x')) 运行结果:xxxxhello练习:zfill()
test='hello' print(test.zfill(9)) #不能指定字符填充,会报错,默认0填充 运行结果:0000hello练习:strip()、rstrip()、lstrip()
test=' hello ' #字符串左右各加一个空格 print(test.strip()) print(test.rstrip()) print(test.lstrip()) 运行结果: hello #去除两边空格 hello #去除右边空格 hello #去除左边空格练习:format()
test="{} name is {}" print(test.format('my','xiaoming')) 运行结果:my name is xiaoming test="{} name is {}" print(test.format('your','daming')) 运行结果:your name is daming2.字符串的变形
upper将字符串中所有的字母转换为大写lower将字符串中所有的字母转换为大写swapcase将字符串中所有的字母大小写互换title将字符串中单词首字母大写,单词以非字母划分capitalize只有字符串的首字母大写expandtabs将字符串中的tab符号(‘\t’)转换为空格,tab符号(‘\t’)默认的空格数是8,可以试下8,可以试下8,12练习:upper()、lower()、swapcase()
print('hello'.upper()) print('HELLO'.lower()) print('heLLo'.swapcase()) 运行结果:HELLO hello HEllO练习:title()、capitalize ()
print('hello world'.title()) print('helloworld '.title()) 运行结果:Hello World Helloworld print('hello world '.capitalize()) print('helloworld '.capitalize()) 运行结果:Hello world Helloworld练习:
print('hello \t world '.expandtabs(10)) print('hello \t world '.expandtabs()) print('hello \t world '.expandtabs(4)) 运行结果:hello world hello world hello world