数据类型—字符串
1、创建: S = 'Hello,beauty.How are you?'
特点:有序,不可变
>>> s = 'Hello World!' #大写变小写,小写变大写
>>> s.swapcase()
'hELLO wORLD!'
>>> s = 'hello WORld' #首字母大写,其余小写
>>> s.capitalize()
'Hello world'
>>> s = 'Hello World!' #全变为小写,不区分大小写
>>> s.casefold()
'hello world!'
>>> s = 'Hello World!'
>>> s.center(40,'*')
'**************Hello World!**************'
>>> s = 'Hello World!'
>>> s.count('l')
3
>>> s.count('l',0,4)
2
>>> s = 'Hello World!'
>>> s.endswith('!')
True
>>> s.endswith('!a')
False
>>> s = 'Hello World!'
>>> s.find('o')
4
>>> s.find('dsa')
-1
>>> s.find('o',5,8)
7
>>> s2 = 'my name is {0},i am {1} years old'
>>> s2.format('李宏',25)
'my name is 李宏,i am 25 years old'
>>> s2 = 'my name is {name},i am {age} years old'
>>> s2.format(name = 'lihong',age = 25)
'my name is lihong,i am 25 years old'
>>> s = 'Hello World!'
>>> s.index('o')
4
>>> s.index('o',5,8)
7
>>> '22'.isalnum() #判断是不是阿拉伯字符
True
>>> '22d'.isalnum()
True
>>> '33d%'.isalnum()
False
>>> '22'.isalpha() #判断是不是阿拉伯字母
False
>>> 'asd'.isalpha()
True
>>> '33'.isdecimal() #判断是不是整数
True
>>> '33.3'.isdecimal()
False
>>> '33g'.isdecimal()
False
>>> 's444'.isidentifier() #判断变量名是否合法
True
>>> '555'.isidentifier()
False
>>> 'ssd123'.islower() #判断是不是只有小写
True
>>> 'Qwre'.islower()
False
>>> names = ['alex','jack','rain'] #将列表转换成字符串之后的连接方式
>>> '-'.join(names)
'alex-jack-rain'
>>> ' '.join(names)
'alex jack rain'
>>> s #脱去空格,换行,tab键
'Hello World! '
>>> s.strip()
'Hello World!'
>>> str_in = 'abcdef'
>>> str_out = '!@#$%^'
>>> str.maketrans(str_in,str_out) #生成对应表
{97: 33, 98: 64, 99: 35, 100: 36, 101: 37, 102: 94}
>>> s
'Hello World! '
>>> table = str.maketrans(str_in,str_out)
>>> table
{97: 33, 98: 64, 99: 35, 100: 36, 101: 37, 102: 94}
>>> s.translate(table) #进行翻译
'H%llo Worl$! '
>>> s = 'Hello world!'
>>> s.replace('o','*',1)
'Hell* world!'
>>> s.replace('o','#')
'Hell# w#rld!'
>>> s
'Hello world!'
>>> s.split() #将字符串转换为列表,默认已空格划分
['Hello', 'world!']
>>> s.split('o') #将字符串转换为列表,以'o'划分
['Hell', ' w', 'rld!']
>>> s2 = 'alex\na\nd\nshanshan\n' #将字符串转换为列表,按行来划分
>>> s2.splitlines()
['alex', 'a', 'd', 'shanshan']
python中的 and 和 or
# and中含0,返回0; 均为非0时,返回后一个值;
>>> 6 and 0
0
>>> 5 and 6
6
>>> 7 and 4
4
# or中, 至少有一个非0时,返回第一个非0;
>>> 3 or 0
3
>>> 4 or 5
4
>>> 0 or 6
6
>>> 0 or 0
0
python中的isdigit函数
#isdigit函数用来判断字符串中是否只含有数字
>>> '123abc'.isdigit()
False
>>> '123456'.isdigit()
True
>>> '123.123'.isdigit() #字符串中含有".",所以为False
False
浙公网安备 33010602011771号