Python-字符串

Posted on 2018-01-24 11:14  常珂  阅读(77)  评论(0编辑  收藏  举报

strip   移除空白

name = '    changke'
print(name)
print(name.strip())

 

len     显示字符串长度

name = 'changke'
print(len(name))#显示字符串的长度

 

索引

name = 'changke'
print(name[2])#输出name的下标为2的字符串

 

切片

name = 'changke'
print(name[0:5])#输出'chang',切片的原则为含头不含尾

 

用+拼接

name = 'changke'
age = '24'
#我们想打印出'my name is changke and i am 24 years old',可以用拼接的方式
msg = 'my name is ' + name + ' and i am ' + age + ' years old'
print(msg)
#使用+拼接字符串时会增加调用内存的次数,影响速度

 

格式化输出

name = 'changke'
age = '24'
#我们想打印出'my name is changke and i am 24 years old'
msg = 'my name is %s and i am %syears old'%(name,age)
print(msg)
#   %为占位符
captalize:首字母大写
name = 'changke'
print(name.capitalize()) #首字母大写

swapcase:大小写翻转

name = 'changke'
print(name.swapcase()) #大小写翻转

每个单词的首字母大写

msg='my name is changke'
print(msg.title()) #每个单词的首字母大写

 

后续更新......