python--基本类型之字符串

String(字符串):

定义和创建字符串:

定义:字符串是一个有序的字符的集合,用于存储和表示基本的文本信息。
注意:字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内

var1='Hello World!'
print (var1)

 

对应操作:

1,“*”重复输出字符串
print('Hello World'*2)
2,"[]","[:]" 通过索引获取字符串中字符,这里和列表的切片操作是相同的
print('Hello World'[2: ])
3, "in" 成员运算符 如果字符串中包含给定字符返回 True
print('el' in 'Hello World')
4,"%"格式字符串
print('alex is a good teacher')
print('%s is a good teacher' %'alex')
5,"+" 字符串拼接
a ='123'
b='abc'
c=a+b
print(c)
注:“+”效率低,改用 join
c=''.join([a,b])
print(c)

 

字符串常用方法:

字符串的替换、删除、截取、复制、连接、比较、查找、分割

#capitalize:首字母大写,其他字母小写
s='asf sgs SD dfs ASdf'
print(s.capitalize())
>>Asf sgs sd dfs asdf

#lower() 转换为小写
#upper() 转换为大写
#swapase() 大小写互换
a='hello word'
print(a.upper())
b='HELLO WORD'
print(b.lower())
c='hello WORD'
print(c.swapcase())
>>HELLO WORD
>>hello word
>>HELLO word

#s.strip():删除字符串两边的指定字符,默认为空值
s=' hello '
b=s.strip()
print(b)
>>hello

#s.lstrip():删除字符串左边的指定字符,
#s.rstrip():删除字符串左边的指定字符,
s=' hello '
b=s.ltrip()
c=s.rtrip()
print(b)
print(c)
>>hello
>> hello

#复制字符串
a='hello'
b=a*2
print(b)
>>hellohello

#连接2个字符串str.join
a='hello'
b='123'
a.join(b)
print(a.join(b))
>>1hello2hello3

#查找字符串str.index;str.find功能相同。
区别在于index查找不到,报错。find查找不到返回‘-1’.两个找到,都返回第一个找的的位置
a='hello word'
print(a.index('w'))
print(a.find('a'))
>>6
>>-1

#判断是否包含指定字符串‘in’,‘not in’
a='hello word'
print('hello' in a)
print('hello' not in a)
>>True
>>False

#查看字符串的长度 len
a='hello word'
print(len (a))
>>10

#srt.centen 将字符串放入中心位置可指定长度以及位置两边字符
a='chen zheng'
print(a.center(20,"*"))
>>*****chen zheng*****

#str.count() 统计字符串出现的次数
a='hello word'
print(a.count('l'))
>>2

#
S='prefix123aaasuffix'
print(S.startswith('prefix')) #是否以prefix开头
print(S.endswith('suffix')) #以suffix结尾
print(S.isalnum()) #是否全是字母和数字,并至少有一个字符
print(S.isalpha()) #是否全是字母,并至少有一个字符
print(S.isdigit()) #是否全是数字,并至少有一个字符
print(S.isspace()) #是否全是空白字符,并至少有一个字符
print(S.islower()) #S中的字母是否全是小写
print(S.isupper()) #S中的字母是否便是大写
print(S.istitle()) #S是否是首字母大写的

posted @ 2018-09-18 16:04  Aron.chen  阅读(188)  评论(0编辑  收藏  举报
Counters
Childrens Vitamins