python入门到放弃(四)-基本数据类型之str字符串

1.概念

python中用',",''',"""引起来的内容称为字符串,可以保存少量数据并进行相应的操作

 

#先来看看str的源码写了什么,方法:按ctrl+鼠标左键点str

class int(object):
    """
    int(x=0) -> int or long
    int(x, base=10) -> int or long
    
    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is floating point, the conversion truncates towards zero.
    If x is outside the integer range, the function returns a long instead.
    
    If x is not a number or if base is given, then x must be a string or
    Unicode object representing an integer literal in the given base.  The
    literal can be preceded by '+' or '-' and be surrounded by whitespace.
    The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
    interpret the base from the string as an integer literal.
    >>> int('0b100', base=0)
    """
    def bit_length(self): 
        """ 返回表示该数字的时占用的最少位数 """
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ 返回该复数的共轭复数 """
        """ Returns self, the complex conjugate of any int. """
        pass

    def __abs__(self):
        """ 返回绝对值 """
        """ x.__abs__() <==> abs(x) """
        pass

    def __add__(self, y):
        """ x.__add__(y) <==> x+y """
        pass

    def __and__(self, y):
        """ x.__and__(y) <==> x&y """
        pass

    def __cmp__(self, y): 
        """ 比较两个数大小 """
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __coerce__(self, y):
        """ 强制生成一个元组 """ 
        """ x.__coerce__(y) <==> coerce(x, y) """
        pass

    def __divmod__(self, y): 
        """ 相除,得到商和余数组成的元组 """ 
        """ x.__divmod__(y) <==> divmod(x, y) """
        pass

    def __div__(self, y): 
        """ x.__div__(y) <==> x/y """
        pass

    def __float__(self): 
        """ 转换为浮点类型 """ 
        """ x.__float__() <==> float(x) """
        pass

    def __floordiv__(self, y): 
        """ x.__floordiv__(y) <==> x//y """
        pass

    def __format__(self, *args, **kwargs): # real signature unknown
        pass

    def __getattribute__(self, name): 
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        """ 内部调用 __new__方法或创建对象时传入参数使用 """ 
        pass

    def __hash__(self): 
        """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
        """ x.__hash__() <==> hash(x) """
        pass

    def __hex__(self): 
        """ 返回当前数的 十六进制 表示 """ 
        """ x.__hex__() <==> hex(x) """
        pass

    def __index__(self): 
        """ 用于切片,数字无意义 """
        """ x[y:z] <==> x[y.__index__():z.__index__()] """
        pass

    def __init__(self, x, base=10): # known special case of int.__init__
        """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
        """
        int(x=0) -> int or long
        int(x, base=10) -> int or long
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is floating point, the conversion truncates towards zero.
        If x is outside the integer range, the function returns a long instead.
        
        If x is not a number or if base is given, then x must be a string or
        Unicode object representing an integer literal in the given base.  The
        literal can be preceded by '+' or '-' and be surrounded by whitespace.
        The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
        interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        # (copied from class doc)
        """
        pass

    def __int__(self): 
        """ 转换为整数 """ 
        """ x.__int__() <==> int(x) """
        pass

    def __invert__(self): 
        """ x.__invert__() <==> ~x """
        pass

    def __long__(self): 
        """ 转换为长整数 """ 
        """ x.__long__() <==> long(x) """
        pass

    def __lshift__(self, y): 
        """ x.__lshift__(y) <==> x<<y """
        pass

    def __mod__(self, y): 
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, y): 
        """ x.__mul__(y) <==> x*y """
        pass

    def __neg__(self): 
        """ x.__neg__() <==> -x """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): 
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __nonzero__(self): 
        """ x.__nonzero__() <==> x != 0 """
        pass

    def __oct__(self): 
        """ 返回改值的 八进制 表示 """ 
        """ x.__oct__() <==> oct(x) """
        pass

    def __or__(self, y): 
        """ x.__or__(y) <==> x|y """
        pass

    def __pos__(self): 
        """ x.__pos__() <==> +x """
        pass

    def __pow__(self, y, z=None): 
        """ 幂,次方 """ 
        """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
        pass

    def __radd__(self, y): 
        """ x.__radd__(y) <==> y+x """
        pass

    def __rand__(self, y): 
        """ x.__rand__(y) <==> y&x """
        pass

    def __rdivmod__(self, y): 
        """ x.__rdivmod__(y) <==> divmod(y, x) """
        pass

    def __rdiv__(self, y): 
        """ x.__rdiv__(y) <==> y/x """
        pass

    def __repr__(self): 
        """转化为解释器可读取的形式 """
        """ x.__repr__() <==> repr(x) """
        pass

    def __str__(self): 
        """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
        """ x.__str__() <==> str(x) """
        pass

    def __rfloordiv__(self, y): 
        """ x.__rfloordiv__(y) <==> y//x """
        pass

    def __rlshift__(self, y): 
        """ x.__rlshift__(y) <==> y<<x """
        pass

    def __rmod__(self, y): 
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, y): 
        """ x.__rmul__(y) <==> y*x """
        pass

    def __ror__(self, y): 
        """ x.__ror__(y) <==> y|x """
        pass

    def __rpow__(self, x, z=None): 
        """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
        pass

    def __rrshift__(self, y): 
        """ x.__rrshift__(y) <==> y>>x """
        pass

    def __rshift__(self, y): 
        """ x.__rshift__(y) <==> x>>y """
        pass

    def __rsub__(self, y): 
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rtruediv__(self, y): 
        """ x.__rtruediv__(y) <==> y/x """
        pass

    def __rxor__(self, y): 
        """ x.__rxor__(y) <==> y^x """
        pass

    def __sub__(self, y): 
        """ x.__sub__(y) <==> x-y """
        pass

    def __truediv__(self, y): 
        """ x.__truediv__(y) <==> x/y """
        pass

    def __trunc__(self, *args, **kwargs): 
        """ 返回数值被截取为整形的值,在整形中无意义 """
        pass

    def __xor__(self, y): 
        """ x.__xor__(y) <==> x^y """
        pass

    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分母 = 1 """
    """the denominator of a rational number in lowest terms"""

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 虚数,无意义 """
    """the imaginary part of a complex number"""

    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分子 = 数字大小 """
    """the numerator of a rational number in lowest terms"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 实属,无意义 """
    """the real part of a complex number"""

int
int

 

2.字符串的索引和切片

#索引

#索引就是下标,切记,下标从0开始
s = "大河向东流去"
print(s[0])  #大  #从0开始取
print(s[1])  #
print(s[2])  #
print(s[3])  #
print(s[4])  #
print(s[5])  #
print(s[6])  #索引不能超过边界,要不然会报错

print(s[-1])  #-1就是倒着从后面取
print(s[-2])
print(s[-3])
print(s[-4])
print(s[-5])
print(s[-6])

#切片

#切片[起始位置:结束位置]
#特点:1、顾头不顾尾
      2、只能从左往右切

#例子:
s = "改革春风吹满面"
print(s[1:3]) #从1切到3,但是取不到3
#革春 #因为是下标从0开始,所以1就是革
print(s[1:]) #从1开始切,切到结尾 #革春风吹满面

print(s[:2]) #从头开始切到2
#改革

print(s[:]) #从头到尾
#改革春风吹满面
print(s[-1:-3]) #这样从右往左切会是空值 print(s[-3:-1]) #只能从左往右切
#吹满

#跳着取值,步长

#步长:如果是整数,就从左往右取,如果是负数就从右往左取
print(s[-1:-3:-1]) # - 表示反方向,从右往左
print(s[3:9:2])    #表示3到9中间每隔2位取一个
print(s[4:10:3])   #表示4到10中间每隔3取一位
print(s[-3:-9:-2]) #从右往左每个2位取一个

 

3.字符串相关操作

#注意点:

#注意:字符串是不可变的对象,所有任何操作对源字符串是不会有任何影响的
#例如
s = "I am a teacher"
s.capitalize()
print(s) #I am a teacher

 

#1.大小写的相互转换

#关键字
# capitalize():将首字母变成大写
# lower():全部替换成小写
# upper():全部替换成大写
# swapcase():大小写互换
# casefold():转换成小写
# titile():每个被特殊字符隔开的首字母大写

#例子:

s = "This is teacher and Student"


s1 = s.capitalize()  #将首字母变成大写
print(s1) #This is teacher and student

s2 = s.lower()   #全部转换成小写
print(s2) #this is teacher and student

s3 = s.upper()  #全部转换成大写
print(s3) #THIS IS TEACHER AND STUDENT

s4 = s.swapcase() #大小写互相转换
print(s4) #tHIS IS TEACHER AND sTUDENT

s5 = s.casefold()  #转换成小写,这个能识别出所有字母,但lower有些不支持
print(s5) #this is teacher and student
View Code

 

#2.切来切去

#关键字
# center():内容居中
# strip():去掉左右两端的空格
# lstrip():去掉左边的空格
# rstrip():去掉右边的空格
# replace(old,new):字符替换
# split():切割

#例子:

#1.拉长的长度:center()
s = "nb"
s1 = s.center(10,"#") #强行使用#号在原字符串左右两端进行拼接,拼接成10个单位
print(s1)

# 更改tab的长度
s6 = "alex wusir\teggon"
print(s6)
print(s6.expandtabs())    # 可以改变\t的⻓长度, 默认⻓长度更更改为8

#2.去空格
s = "  guoke  boy  is  "
s1 = s.strip()  #默认去掉两边的空格
print(s1)  #打印出来的时候就会发现两边没有空格

s2 = s.lstrip()  #去掉左边的空格
print(s2)

s3 = s.rstrip()  #去掉右边的空格
print(s3)

#strip()应用
# 设置用户交互式登陆的时候,如果不加strip(),当用户如输入用户名后面加了空格,那么就会报错
# 如果加了strip(),就可以去掉两边的空格
username = input("请输入用户名:").strip()
password = input("请输入密码:").strip()
if username == 'cw' and password == '123':
    print("登陆成功")
else:
    print("登陆失败")

#指定去掉的元素
s = "nb boy guoke nb nb tiantian sb"
print(s.strip("nb"))

#3.字符串替换:replace()
s = "student,战狼,teacher,小猪佩奇_eat,少年的你"
s1 = s.replace("少年的你","中国机长")  #将少年的你替换成中国机长
s2 = s.replace("小猪","猫猫")  #将小猪替换成猫猫
print(s1,s2)

s3 = s.replace('e','nb',2)  #将e替换成nb,替换前两个
print(s3)

#4.字符串切割:split()
s4 = "fd,fwe,tet,rer,aggo"
lst = s4.split(",")  #字符串切割,根据,进行切割
print(lst)
 
s5 = s4.split("e")  #使用什么进行切割就会损失掉什么
print(s5)


#坑点
# s7 = "湖边哈哈美丽美丽湖人湖边"
# lst = s7.split("湖边") #如果切割符在左右两端,那么一定会出现空字符串
# print(lst)
# print(bool(lst)) #可以看到返回是True,因为是空字符串
View Code

 

#3.查找相关

#关键字:
# startswith():判断是否以xxx开头
# endswith():判断是否以xxx结尾
# count():查看那个字符出现的次数
# find():查看关键字在什么位置,没有找到的话就返回-1
# index():求索引的位置:如果没找到字符串就会报错

#例子:

s = "我是一个boy,我喜欢python,java等编程语言"

s1 = s.startswith("我是一个")  #判断是否以我开头,如果是就会返回True,否则返回False
print(s1) #True

s2 = s.startswith("boy")  #可以看出返回的结果是False
print(s2) #False

s3 = s.endswith("语言")  #判断是否以"语言"位结尾,是就会返回True,否则返回False
print(s3) #True

s4 = s.endswith("我们")  #可以看出不是以我们结尾就返回False
print(s4) #False

s5 = s.count("a")  #统计"a"出现的次数
print(s5) #2

s6 = s.find("java")  #查看Java出现的位置,只找第一次出现的位置,没有就返回-1
print(s6) #18

s7 = s.find("a",20,29)  #切片找,指定位置找a,从20-29中间找有没有a
print(s7) #21

s8 = s.index("java")   #查找java的位置
print(s8) #18

# s9 = s.index("z")  #index如果没有查找到的话就会报错,写程序的就不用使用index,否则整个程序都会崩掉了,使用find
# print(s9)
View Code

 

#4.条件判断相关

#关键字
# isalnum():判断是否由字母和数字组成
# isalpha():判断是否由字母组成
# isdigit():判断是否由数字组成
# isdecimal():判断是否由数字组成
# isnumeric():判断是否由数字组成 #中文也识别

#例子:

s1 = "12345"
s2 = "123abc"
s3 = "abcde"
s4 = "_abdf@"
s5 = "壹仟叁佰肆拾"
print(s1.isdigit())  #判断是否由数字组成,如果是就返回True,否则Fase
#True
print(s2.isalnum())  #判断是否由数字和字母组成
#True
print(s3.isalpha())  #判断是否由字母组成
#True
print(s5.isnumeric()) #判断是否由数字组成,可以是大写的,如果是字符串就报错
#True
print(s1.isdecimal()) #判断是否由数字组成
#True

#练习,用算法判断某一个字符串是否是小数
s17 = "-123.12"
s17 = s17.replace("-", "")  # 替换掉负号
if s17.isdigit():
    print("是整数")
else:
    if s17.count(".") == 1 and not s17.startswith(".") and not s17.endswith("."):
        print("是⼩小数")
    else:
        print("不不是⼩小数")
#过程理解:首先将符号替换成空字符串,然后进入判断变量是否是数字组成
#很显然是没有由数字组成,所有就走else,又进入如果判断,如果统计点符号等于1
#和不是以点开头和不是以点结尾,满足条件,所以打印是小小数
View Code

 

#5.计算字符串的长度

#关键字
#len():计算机字符串的长度

#例子:

s1 = "我是你的小呀小苹果"
ret = len(s1)
print(ret) #9
#注意:len()是python的内置函数,所以访问方式也不一样,记住len()和print()方式一样

 

#6.join

#join:将列表转换成字符串
#注意:join(里面放的是可迭代对象)

#例子

 lst = ["蒋小雨","张冲","鲁炎"] s = "_".join(lst) print(s) #蒋小雨_张冲_鲁炎

 s = "_".join("武黑脸") print(s) #武_黑_脸

#将字符串转换成列表:split() s = "马云,移动,雷子" lst = s.split(",") print(lst) #['马云', '移动', '雷子']

 

posted @ 2020-03-08 19:55  老油条IT记  阅读(381)  评论(0编辑  收藏  举报
levels of contents