Hr_chram

导航

 

str的基本使用

1、用途:用于记录描述性质的状态

 

2、定义方式:在"",'',""" """,''' ''',内包含一串字符

test = 'skajgfnsaa'

age = '18'   # age = str('18')

print(test,type(test))

print(age,type(age))

数据类型转换:可以把任意类型转换成str类型
res = str([1,2,3])
print(res,type(res))

3、常用操作+内置方法
#优先掌握的操作:
#1、按索引取值(正向取+反向取):只能取,不能改
msg = 'hello world'
print(msg[0])
print(msg[-1])
print(msg)
msg[0] = 'H'   #报错

2、切片(顾头不顾尾,步长)
msg = 'hello world'
print(msg[0:5])
print(msg[0:5:2]) #0 2 4  hlo
print(msg)


print(msg[:])    拷贝完整字符串
print(msg[-1:-4:-1])
print(msg[::-1])    #将字符串倒过来



3、长度len
#msg = 'a 他'
print(len(msg))
4、成员运算in和not in
msg = 'hello world'
print('wo' in msg)
print('o ' in  msg)
print(not 'wl' in msg)
print('wl' not in msg)


5、移除空白strip
msg = '     hello     '
print(smg)
test = msg.strip()
print(test)
print(msg)


# msg = "***hello******"
# msg = "**+-/?*h*-ello**?-**&^**"
# print(msg.strip("^&*+-/?"))


inp_user = input('请输入账号').strip
inp_user_1 = input('请输入密码').strip
if inp_user == 'alex' and inp_user_1 == '123':
    print('ok')
else:
    print('no')


6、切分split (str转变为列表)

msg = 'egon:18:male'
res = msg.split(':')
print(res[0])
print(res)

res = msg.split(':',1)
print(res)




info = ['egon',18,'male']
res1 = '%s:%s:%s' %(info[0],info[1],info[2])
res1 = ':'.join(info)  ===>str + str +str(适用于都是字符串的,没有整形等) 
print(res1)
7、循环 msg = 'egon:18:male' for x in msg: print(x) 类型总结 存一个值or存多个值 有序or无序 可变or不可变(1、可变:值变,id不变。可变==不可hash 2、不可变:值变,id就变。不可变==可hash)

 

posted on 2021-03-17 18:46  遮光镜  阅读(46)  评论(0编辑  收藏  举报