Python基本数据类型——字符串

我们知道python的基本数据类型有:字符串,整型,列表,元组,字典,集合。从类型分为可变数据类型和不可变的数据类型。

可变数据类型:列表,字典

不可变数据类型:字符串,元组。集合有可变和不可变集合

接下来我们一一学习,先来学习字符串,python中字符串的标识为''或者""被单引号或者双引号引起来的字符为字符串,例如

>>> test="hello"
>>> type(test)
<class 'str'>  #type是查看类型的内置方法
>>> dir(test)  #test为查看该对象支持哪些方法
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> id(test)  #id是查看内存地址
45850104

接下来我们一一学习字符串的方法

1:查看字符串的长度
>>> a="hello world"
>>> len(a)  #空格也算
11
2:统计某个元素出现的次数
>>> a="hello world"
>>> a.count('l')
3
3:查看某个字符的索引位置(两种方法)
#方法1
>>> a.index('e')
1
>>> a.index('c')
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    a.index('c')
ValueError: substring not found
#方法2
>>> a.find('e')
1
>>> a.find('c')
-1
注意:index如果查找的元素不存在,直接抛出异常。但是find如果查找元素不存在结果为-1
4:将字符串的首字母大写
>>> a.capitalize()
'Hello world'
5:将字符串全部改为大写
>>> a.upper()
'HELLO WORLD'
6:将字符串全部改为小写
>>> a.lower()
'hello world'
7:将字符串的大小写互换
>>> a="Hello World"
>>> a.swapcase()
'hELLO wORLD'
8:判断字符串是否以某个字符开头
>>> a.startswith('H')
True
9:判断字符串是否以某个字符结尾
>>> a.endswith('D')
False
10:判断字符串是否都为小写
>>> a.islower()
False
11:判断字符串是否都为大写
>>> a.isupper()
False
12:判断字符串是否都为数字
>>> a.isdigit()
False
13:判断字符串是否都为字母(汉字也为字母)
>>> a="哈哈abc"
>>> a.isalpha()
True
14:判断字符串是否是字母和数字的组合(只有数字或者字母也为真,汉字也为真)
>>> a="哈哈123"
>>> a.isalnum()
True
15:将字符串转换为列表
>>> a.split()
['哈哈123']
>>> a.split('2')  #split可以指定分隔符
['哈哈1', '3']
>>> list(a)
['哈', '哈', '1', '2', '3']
16:去掉字符串两边的字符(默认为空格和回车)
>>> a=" hello world\n"
>>> a.strip()
'hello world'
>>> a="!hello world"
>>> a.strip('!')
'hello world'
17:字符串的拼接
%s  表示是字符
%d  类型必须是数字
%f  浮点型
format|format_map 内置方法
>>> a="hello"
>>> b="world"
>>> a+b
'helloworld'
>>> print("%s,+,%s" %(a,b))
hello,+,world
>>> a,b
('hello', 'world')
#format方法
>>> name="heitao"
>>> age=23
>>> print("{Name}今年{Age}" .format(Name=name,Age=age))
heitao今年23
#format_map方法
>>> print("{Name}今年{Age}" .format_map({"Name":name,"Age":age}))
heitao今年23
18:将字符串居中
>>> a="info"
>>> a.center(20,"#")  #20为总长度,#为填充字符
'########info########'
19:join字符串拼接
>>> "_".join(a)  #类型必须统一
'i_n_f_o'
20:替换某个元素
>>> a="hello world"
>>> a.replace("l","L")
'heLLo worLd'
####################################切片操作
1:截取整个字符串
>>> a[0:]
'hello world'
2:截取第一个字符
>>> a[0]
'h'
3:截取最后一个字符
>>> a[-1]
'd'
4:截取指定间距的字符
>>> a
'hello world'
>>> a[0:4]
'hell'
>>> a[0:6:2]   #2为步长
'hlo'
5:截取除最后一个的字符串
>>> a
'hello world'
>>> a[:-1]
'hello worl'
6:将字符串倒叙
>>> a[::-1]
'dlrow olleh'

以上就是常用的字符串的操作方法,接下来我们进行遍历字符串

>>> for i in a:
	print(a.index(i),i)

	
0 h
1 e
2 l
2 l
4 o
5  
6 w
4 o
8 r
2 l
10 d

接下来我们做一个练习,需求如下
1:输入一个字符串,遍历整个字符串并打印出每个字符的索引位置
2:输出整个字符串中有多少个数字,字母和特殊字符,查找字符串中是否有重复的字符,查找出重复字符的索引位置

代码实现如下:

#!/usr/bin/python3
#coding=utf8
#Author:HeiTao


str_test=input("输入一个字符串: ")
A=""
B=""
C=""
#遍历字符串
print("索引\t字符".expandtabs(15))
# for i in str_test:
#     print("%d\t%s".expandtabs(20)%(str_test.index(i),i))
for a,b in enumerate(str_test):
    print("%d\t%s".expandtabs(20)%(a,b))
    #判断是否有重复字符
    if str_test.count(b) > 1:
        if b not in C:
            C+=b
    if b.isalpha():
        B+=b
    elif b.isdigit():
        A+=b
print("字母有%s个"%len(B))
print("数字有%s个"%len(A))
print("特殊字符有%s个"%(len(str_test)-len(A)-len(B)))

#重复字符个数
for i in C:
    print("重复字符%s有%d个"%(i,str_test.count(i)))

find_str=input("输入您要查找的字符: ")
if find_str not in str_test:
    print(find_str+"不存在与{test}中".format(test=str_test))
else:
    print("%s的索引位置是%s"%(find_str,str_test.index(find_str)))

猜你喜欢

转载自blog.csdn.net/spades_linux/article/details/81081559