03_字符串,列表,字典

一、字符串

  (1)字符串类型的转换
//将数值转转为字符串类型
num = 100 to_string = str(num)
//将字符串类型转换为数值类型
str = "100"
num = int(str)
  (2)输入,输出字符串
//输入
username = input("请输入用户名:")
//输出
print("用户名为:%s"%username)

password = input("请输入密码:")
print("密码为:%s"%password)
  (3)组成字符串的两种方式
//方式1
A = 100 B = 200 C = A +B //结果为300 a = 'lao' b = 'wang' e = "===" + a + b + "===" //结果为 '===laowang==='
//方式2 f = '===%s==='%(a+b) //结果为'===laowang==='
  (4)字符串中的下标

  字符串中的元素下标从0开始

name = 'abcdef'
name[0] //值为'a'
name[1] //值为'b'

  

//判断字符串的长度
name = 'abcdef'
length = len(name) //长度为6

  

//从字符串最后往前取
name = 'abcdef'
name[-1] //值为'f'
name[-2] //值为'e'

//或者
name[len(name)-1] //值为'f'
  (5)切片,字符串逆序(倒序)
//切片
name = 'abcdefABCDEF' name[2:5] //结果为'cde',包左不包右 name[2:-2] //'cdefABCD' name[2:0] //'' name[2:] //'cdefABCDEF' name[2:-1] //'cdefABCDE' name[2:-1:2] //[起始位置:终止位置:步长],结果为'ceACE'

  

//倒序
name = 'abcdefABCDEF'
name[-1::-1] //-1为最后,:为第一个,步长为-1才能取到结果,结果为'FEDCBAfedcba'
name[::-1] //'FEDCBAfedcba'
  (7)字符串常见操作

  字符串查找<find><index>

myStr = 'hello world itcast and itcast xxxcpp'

myStr.find('world') //结果为6,查找world在myStr的开始位置

myStr.find('dongge') //找不到时为-1

myStr.find('itcast') //12,找到'itcast'第一次出现的位置

myStr.rfind('itcast') //23,从右边开始找'itcast'

  

myStr = 'hello world itcast and itcastxxxcpp'

myStr.index('world') //6

myStr.index('donge') //找不到时返回 substring not found

myStr.rindex('itcast' ) //23,从右边开始找

  统计次数<count>

myStr = 'hello world itcast and itcastxxxcpp'
myStr.count('itcast') //2

  替换<replace>

myStr = 'hello world itcast and itcastxxxcpp'
myStr.replace('world','WORLD') //'hello WORLD itcast and itcastxxxcpp'

myStr //结果不会变,因为字符串不可变

myStr.replace('itcast','xxx') //'hello world xxx and xxxxxxcpp' itcast被全替换成xxx

myStr.replace('itcast','xxx',1) //'hello world xxx and xxxxxxcpp',只替换第1次出现的itcast

  切割<split>

myStr = 'hello world itcast and itcastxxxcpp'
myStr.split(" ") //['hello','world','itcast','and','itcastxxxcpp']

  字符串中第一字符大写<capitalize>

myStr = 'hello world itcast and itcastxxxcpp'
myStr.captialize() //'Hello world itcast and itcastxxxcpp'

  字符串中每个单词首字母大写<title>

a  = 'hello itcast'
a.title() //'Hello Itcast'

  检查是否以某字符串开头,返回为True或False <startswith>

myStr = 'hello world itcast and itcastxxxcpp'

myStr.startswith('hel') //True

myStr.startswith('eee') //False

  检查是否以某字符串开头,返回为True或False <endswith>

myStr = 'hello world itcast and itcastxxxcpp'

myStr.endswith('pp') //True

myStr.endswith('ppp') //False

  将所有大写转为大写 <lower>

myStr.lower()

  将所有小写转为小写 <upper>

myStr.upper()

  将字符串居中显示 <center>

myStr.center(50) //50为总的字符串长度

  将字符串靠左显示 <ljust>

myStr.ljust(50)

  将字符串靠右显示 <ljust>

myStr.ljust(50)

  删除字符串左边空格 <lstrip>

myStr.lstrip()

  删除字符串右边空格 <rstrip>

myStr.rstrip()

  删除字符串两边空格 <strip>

myStr.strip()

  以字符串分割字符串 <partition>

猜你喜欢

转载自www.cnblogs.com/rongpeng/p/9007656.html
今日推荐