python 字符串

字符串是python中最常见的数据类型,一般使用单引号( ' ' )或是双引号( " " )来创建

创建字符串:

1  var1="Hello Word"
2  var2='Adair'

 python中单引号( ' ' )或是双引号( " " )没有区别,可以相互嵌套使用。

 

查看字符串中的元素:


1 print(str2[3])  #去某个单独的字符
>>> i
2 print(str1[3:7]) #取某个区间的字符
>>> lo W
3 print(str2[0:4:2]) #每隔一个取某个区间的字符,2为步长。
>>> Aa

字符串的拼接:

1 print(str2[:] + ' ' + "is a handsome boy")
>>> Adair. is a handsome boy

 

python 中使用加号( + ) 进行字符串的拼接。

 

字符串的内置函数:

 1 name = "my \tname is {name}, age is {age}."
 2 
 3 print(name.capitalize())  #将这段话的首字母大写
>>>My name is {name}, age is {age}.
4 print(name.count("a")) #统计指定元素的个数
>>>4
5 print(name.center(50,"-")) #一共打印50个字符,把原始字符串放到中间,两边不够的用“-”补上
>>>--------my     name is {name}, age is {age}.---------
6 print(name.encode()) #转换成二进制格式
>>>b'my \tname is {name}, age is {age}.'
7 print(name.endswith("an")) #判断字符串以什么结尾
>>>False
8 print(name.startswith("my")) #判断字符串以什么开头
>>>True
9 print(name.expandtabs(30)) #把tab键换成30个空格
>>>my                            name is {name}, age is {age}.
10 print(name.find("name")) #获取相关元素的下标
>>>4
11 print(name[name.find("name"):]) #根据下标切片
>>>name is {name}, age is {age}.
12 print(name.format(age=26,name="aaron fan")) #format格式传参
>>>my     name is aaron fan, age is 26.
13 print(name.format_map({'age':26,'name':'aaron fan'})) #以字典的形式传送,结果同format
>>>my     name is aaron fan, age is 26.
14 15 print("Abc123".isalnum()) #判断字符串中是否只有数字和字母
>>>True
16 print("AbCde".isalpha()) #判断字符串中是否只有字母
>>>True
17 print("12391".isdigit()) #判断字符串中是否只有数字
>>>True
18 print("asd_1".isidentifier()) #判断字符串是否是合法的变量名
>>>True
19 print("12331".isnumeric()) #判断字符串是否只有数字
>>>True
20 print(" \t \n".isspace()) #判断字符串是否是空格
>>>True
21 print("Adair Shuai".istitle()) #判断手首写字母是否为大写
>>>True
22 print("Adair_@123".isprintable()) #判断字符串是否能打印
>>>True
23 print("ADWCVF".isupper()) #判断字符串是否为大写
>>>True
24 25 list1 = ["1","2","3","4","5","6"] 26 print("+".join(list1)) #将列表装换成指定格式的字符串
>>>1+2+3+4+5+6
27 28 print(name.ljust(100,"*")) #打印100个字符不够的话用指定符号代替
>>>my     name is {name}, age is {age}.*******************************************************************
29 print("Adair Ye".lower()) #将大写转换成小写
>>>adair ye
30 print("Adair Ye".upper()) #将小写转换成大写
>>>ADAIR YE
31 print("Adair,Ye".swapcase()) #将大写转换成小写,将小写转换成大写
>>>aDAIR,yE
32 print(name.strip()) #去除两边的换行
>>>my name is {name}, age is {age}.
33 print("Adair.Ye".replace("a","0",2)) #替换指定的字符,示例中将“a”替换成“o”,替换两个
>>>Ad0ir.Ye
34 print("asd+qwe+zcxc".split("+")) #将字符串根据指定字符分成一个列表,默认以空格分
>>>['asd', 'qwe', 'zcxc']
35 print("asd\nqwe\nzxc".splitlines()) #根据换行符把字符串分成一个列表
>>>['asd', 'qwe', 'zxc']

 

posted @ 2018-03-06 20:43  叶小黑  阅读(310)  评论(0编辑  收藏  举报