7.3 字符串类型及内置方法

str字符串

用途:描述性

定义方式:

#单引号
s = 'Hello baby'  # 等价于 s = str('Hello baby')

#双引号
k = "xxx"

#三引号
i = """
    xxx
    xxx
    """  # 或者上下用三个单引号
# 需要注意的是只有三引号的内容被变量名接收了才是字符串,不然就是注释
s1 = str([1,2,3,4])
print(s1,type(s1))
>>>>>>>>
[1, 2, 3, 4] <class 'str'>

#任何数据类型(包括列表,字典) 都可以转成字符串类型

内置方法

#1.按索引取值 (可以正向取,也可以反向取)

info = 'hello little one'
#       01234567
print(info[0])  # 第一个的索引是0
>>>h

print(info[7])  # 空格也占索引
>>>i

print(info[-1])  # 负值从右往左数
>>>e

  补充:索引只能取,不能改 (和列表里不同,列表里索引可以取值也可以修改)

#2.切片(顾头不顾尾,步长):从一个大的字符串中截取一段新的小字符串

  左边的固定就是头,右边固定就是尾  并不是按照数字大小来分头尾

info = 'hello little one'
print(info[0:5])  # hello
print(info[0:10:1])  # hello litt 步长不写默认是1
print(info[0:10:2])  # hlolt 步长表示隔几个取一个(这里是每两个取一个)

#了解负数取值
print(info[-1])  # e
print(info[0:4:-2]) # 为空 # 切片取值默认是从左往右的
                    # 这里是从起始位置往左取,所以取不到
print(info[4:0:-1]) # olle 这里是从索引4往左取到索引1
                    # 顾头不顾尾,并不是按照数字大小分头尾,而是按照位置
                    # 所以这里 索引4是头 索引0是尾
print(info[-1:-10:-1])  # eno eltti

#3.长度len:统计的是字符串中字符的个数

s = ' '
print(len(s)) 
>>>
1

#4.成员运算in和not in: 判断一个子字符串是否存在于一个大的字符串中

print('el' in 'hello little one')
>>>
True

print('g' in 'hello little one')
>>>
False

print('bitten' not in 'hello little one')
>>>
True

#5.strip: 去掉字符串左右两边的字符,不管中间的

name1 = 'bitten'
name2 = '   bitten   '.strip()
print(name1 == name2)
>>>
True
username = input('>>>:').strip()
if username == 'bitten':
    print('good job')
#通过这种方法,可以去掉用户输入中多余的空格
name3 = '$$$$$bit$ten$$$$'
print(name3.strip('$'))
>>>
bit$ten
#可以批量去除同一种字符
name4 = '% ¥#bitten&**)'
print(name4.strip('% ¥#)').strip('**&'))  
# 这里strip里面的字符串方向可以改变 #比如把.strip('**&')写成.strip('&**'),也是可以正确去除的 >>> bitten

#6.split: 切分,针对按照某种分隔符组织的字符串,可以用split将其切分成列表,进而进行取值

data = 'bitt en|123| handsome'

print(data.split('|'))  # ['bitt en', '123', ' handsome']
username,password,info = data.split('|')
print(username,password,info)  # bitt en 123  handsome


# 强调:split切分出来的数据类型是一个列表
print(data.split('n'))  # ['bitt e', '|123| ha', 'dsome']
print(data.split('n',1))  # ['bitt e', '|123| handsome']
print(data.rsplit('n',1))  # ['bitt en|123| ha', 'dsome']
# 切割的方向是从左向右的

# 如果不指定那么split和rsplit效果是一样 # 比如下面两个的结果都是['bitt e', '|123| ha', 'dsome'] # print(data.split('n',1)) # print(data.rsplit('n',1))

#7.循环

data = 'bitt en|123| handsome'
for i in data:
    print(i)
b
i
t
t
 
e
n
|
1
2
3
|
 
h
a
n
d
s
o
m
e
result

需要掌握

## 1. strip,lstrip,rstrip

info = '$$$hello little one$$$'
print(info.lstrip('$'))
>>>
hello little one$$$

info = '$$$hello little one$$$'
print(info.rstrip('$'))
>>>
$$$hello little one

## 2. lower,upper

s = 'BiTtEn'
res = s.lower()
print(res)  # bitten
print(s)  # BiTtEn # 调用字符串的方法并没有改变字符串本身
print(s.upper())  # BITTEN
print(s)  # BiTtEn # 调用字符串的方法并没有改变字符串本身

## 3. startswith,endswith

s01 = 'hello little one'
print(s01.startswith('h'))  # True # 判断字符串是否以什么什么开头
print(s01.endswith('n'))  # False # 判断字符串是否以什么什么结尾

## 4. format的三种玩法

# 第一种  按位置占位   跟%s原理一致
str1 = 'my name is {} my age is {}'.format('bitten',18)
str2 = 'my name is {} my age is {}'.format(18,'bitten',)
print(str1)  # my name is bitten my age is 18
print(str2)  # my name is 18 my age is bitten

# 第二种  按索引占位
str3 = 'my {1} name is {0} my {0} age is {0}'.format('bitten',18)
print(str3)  # my 18 name is bitten my bitten age is bitten

# 第三种  指名道姓占位(关键字传参)
str4 = 'my {name} name is {age} my age is {name}'.format(name='bitten',age=18)
print(str4)  # my bitten name is 18 my age is bitten

## 5. split,rsplit

data = 'bitten|kingdom|handsome'
print(data.rsplit('n',2))  # 以's'为切分点,从右往左切了2次
>>>
['bitten|ki', 'gdom|ha', 'dsome']

## 6. join

str1 = ['bitten', '123', 'handsome']
res_str = '$'.join(str1)  # 将容器类型中的多个元素通过指定字符拼接成一个字符串
print(res_str)
>>>
bitten$123$handsome
l = ['k','a','p']
res = '|'.join(l)
print(res)
#区分于split
data = 'bitten|123|handsome'
res_list = data.split('|')
print(res_list)
>>>
['bitten', '123', 'handsome']

## 7. replace

str = 'he is cool and he has a phone'
res = str.replace('he','bitten',1)
print(res)
print(str)

## 8. isdigit

while True:
    age = input('>>>:')
    if age.isdigit():
        age = int(age)
        if age > 28:
            print('大哥大嫂过年好')
    else:
        print('输错了')

需要了解

### 1. find,rfind,index,rindex,count

s = 'latin is cool and latin is kind'
print(s.find('cool'))  # 9 返回的是d字符所在的索引值
print(s.find('xxx'))  # -1 找不到的时候不报错返回的是-1
print(s.find('i',0,3))  # -1 还可以通过索引来限制查找范围
print(s.index('o'))  # 10 返回所传字符所在的索引值
print(s.count('n'))  # 4 统计字符出现的次数

### 2. center,ljust,rjust,zfill

s9 = 'bitten'
print(s9.center(12,'*'))  # ***bitten***
print(s9.ljust(40,'$'))  # bitten$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
print(s9.rjust(40,'$'))  # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$bitten
print(s9.rjust(40,' '))  #                                   bitten
print(s9.zfill(40))  # 0000000000000000000000000000000000bitten

### 3. expandtabs

s10 = 'a\tbc'
print(s10.expandtabs(100))
>>>
a

### 4. captalize,swapcase,title

s12 = 'hElLo WoRLD sH10'
print(s12.capitalize())  # Hello world sh10 # Hello world 首字母大写
print(s12.swapcase())  # HeLlO wOrld Sh10 # 大小写互换
print(s12.title())  # Hello World Sh10 # 每个单词的首字母大小

### 5. is数字系列 

  • isdecimal(): 检查字符串是否值包含十进制字符,如果是返回True,否则返回False
  • isdigit(): 如果字符串只包含数字,则返回True,否则返回False
  • isnumeric(): 如果字符串中只包含数字字符,则返回True,否则返回False 
num1=b'4' #bytes
num2=u'4' #unicode,python3中无需加u就是unicode
num3='' #中文数字
num4='' #罗马数字
# ''.isnumeric(): unicode,中文数字,罗马数字    只要是表示数字都识别
print(num2.isnumeric())  # True
print(num3.isnumeric())  # True
print(num4.isnumeric())  # True

# ''.isdecimal(): unicode   只识别普通的阿拉伯数字
print(num2.isdecimal())  # True
print(num3.isdecimal())  # False
print(num4.isdecimal())  # False

# ''.isdigit() :bytes,unicode    通常情况下使用isdigit就已经满足需求了
print(num1.isdigit())  # True
print(num2.isdigit())  # True
print(num3.isdigit())  # False
print(num4.isdigit())  # False

猜你喜欢

转载自www.cnblogs.com/PowerTips/p/11129367.html
7.3