09字符串(1)

字符串

1 . len
2 . str
str(数据) - 所有的数据都可以转成字符串;转换的时候是在数据的打印值外面加引号
nums = 123
# str(nums) - '123'

nums = 1.23
# str(nums) - 1.23
print(str(nums))

list1 = [10, 20, 30]
print(list1)  # [10,20, 30]
# str(list1) - '[10, 20, 30]'
new_str = str(list1)
print(type(new_str))

list2 = ["abc", 10, 20]
print(list2)  # ['abc', 10, 20]
# str(list2)    - "['abc', 10, 20]"
list3 = ["abc", 10, 20, 'ab']
print(list3)  # ['abc', 10, 20, 'ab']
# str(list3)   - "['abc', 10, 20, 'ab']"

dicts1 = {"abc", 10, 20, 'ab'}
print(dicts1)  # {10, 20, 'ab', 'abc'}
# str(dicts1) -  "{10, 20, 'ab', 'abc'}"

3. eval(字符串) - 获取指定字符串引号中的内容(取到字符串的引号)

注意:这里的字符串去掉引号以后必须是一个合法的表达式
1) 去掉引号以后是合法的数据
eval(‘100’) # 100
nums = '100'
print(type(eval('100')))
# eval('abc')  报错
# eval(’“abc”‘) # “abc”
nums1 = eval('"abc"')
print(type(nums1))

nums2 = eval('[10,20,30]')
print(nums2)
# nums3 = eval('[abc,10,20]')
# print(nums3)  报错  abc不是合法数据

# 2) 去掉引号以后是合法的表达式
nums = eval(('100 + 200'))
print(nums)    # 100 + 200 = 300

abc = 10
nums = eval('abc +10')
print(nums)   # 10 + 10

nums = [10,20,30]
nums1 = eval('nums.append(100)')
print(nums)   # [10,20,30,100]

2 .字符串相关方法

1.join
字符串.join(序列) - 将序列中的元素用指定的字符串连接成一个新的字符串(序列中的元素必须全都是字符串)
list1 = ['hello', 'world', '你好', '世界']
result = ''.join(list1)
print(result)  # helloworld你好世界

result = ','.join(list1)
print(result)  # hello,world,你好,世界

result = '123'.join(list1)
print(result)  # hello123world123你好123世界
result = ' '.join((list1))
print(result)  # hello world 你好 世界

# 练习:将nums中的元素拼接成一个数字
nums = [10,20,30,4,52]
result = ''.join([str(x) for x in nums])
print(int(result))

# 练习:将nums中所有个位数拼成一个数字字符串,’09042‘
nums = [10,29,30,4,52]
result= ''.join([str(x % 10) for x in nums])
print(result)


# 练习:将list1所有数字用’+‘连接,并且计算它们的和 : ’19+1.23+8+22.2‘

list1 = [19,'abc',True,1.23,8,22,'环境']
result = '+'.join([str(x) for x in list1 if type(x) in (int,float)])
print(result,eval(result),sep = '=')

2.split 切割
字符串1.split(字符串2) - 将字符串1所有的字符串2作为切割点对字符串1进行切割,返回一个包含多个字符串的列表
str1 = 'abc123hello123你好123python'
result = str1.split('123')
print(result)   # ['abc', 'hello', '你好', 'python']

# 注意.如果切割点在字符串开头,或者字符串结尾或者连续出现多个切割点都会产生空串
str2 = '123ac123123hello123你好123python123'
result = str2.split('123')
print(result)  # ['', 'ac', '', 'hello', '你好', 'python', '']

str2 = '123ac123123hello123你好123python123'
result = str2.split('123',3)
print(result)   # ['', 'ac', '', 'hello123你好123python123']

3.replace - 替换
字符串1.replace(字符串2, 字符串3) - 将字符串1中所有的字符串2都替换成字符串3
字符串1.replace(字符串2, 字符串3,N)- 将字符串1中前N个字符串2都替换成字符串3
strs='how are you? Im fine, Thank you!'
str3 = strs.replace('you', 'me')
print(str3)

4.strip - 去掉字符串前后的空白字符

字符串.strip()

字符串.strip(字符)

print('-------------------------------------------')
str3 = '   \t  \n    good  good  study      \n      '
str2 = str3.strip()
print(str2)  # good good study

str2= '///good good study'
str3 = str2.strip('/')
print(str3)   # good good study

5.count

字符串1.count(字符串2) - 统计字符串1中字符串2中出现的次数

strs='how are you? Im fine, Thank you!'
print(strs.count('you'))  # 2
print(strs.count('a'))  #  2

# 6.maketrans、translate

str.maketrans(字符串1,字符串2) - 通过字符串1和字符串2创建对应关系表
字符串.translate(对应关系表) - 按照对应关系表将字符串中字符进行替换
table = str.maketrans('abc', '123')
# {97: 49, 98: 50, 99: 51}  a-1 b-2 c-3
str1 = 'aamnbcdbcmn'
result = str1.translate(table)
print(result)  # 11mn23d23mn

6.补充:

1.center、ljust、rjust、zfill
字符串.center(长度,字符) - 将指定字符串变成指定长度,不够用指定字符填充:原字符串放中间
字符串.ljust(长度,字符) - 将指定字符串变成指定长度,不够用指定字符填充:原字符串放左边
字符串.rjust(长度,字符) - 将指定字符串变成指定长度,不够用指定字符填充:原字符串放右边
字符串.zfill(长度) == 字符串.rjust(长度,’0‘)
# abcxxxx、xxxabc 、 xxabcxx
str1 = 'abc'
print(str1.center(7,'x'))  # xxabcxx
print(str1.ljust(7,'x'))   # abcxxxx
print(str1.rjust(7,'x'))   # xxxxabc
print(str1.center(2,'x'))  # abc

nums = '123'
print(nums.zfill(6))   # '000123'

2,find、index
字符串1.find(字符串2) - 获取字符串2在字符串1中第一次出现的位置,如果字符串不存在返回 -1
字符串1.index(字符串2) - 获取字符串2在字符串1中第一次出现的位置,如果字符串2不存在报错!
字符串1.rfind(字符串2) - 从后往前
字符串1.rindex(字符串2) - 从后往前
strs = 'how are you? Im fine, Thank you!'
print(strs.find('you'))  # 8
print(strs.index('you')) # 8

print(strs.find('youu')) # -1
# print(strs.index('youu'))  报错

print(strs.rfind('you'))  # 28
print(strs.rindex('you')) # 28
3.isdigit、isnumEric - 判断是否是纯数字字符串
字符串.isdigit() - 判断字符串中元素是否全是数字字符(0-9)
字符串.isnumeric() - 判断字符串中元素是否全是具有数字意义的字符
str1 = '1234'
print(str1.isdigit())  # True
print(str1.isnumeric())  # True

str1 = '1234一'
print(str1.isdigit()) # False
print(str1.isnumeric()) # True


print('k'.islower()) # 判断字母小写
print('M'.islower()) # 判断字母小写

print('KMsh-23KOP'.upper()) # 字母变成大写
print('KMsh-23KOP'.lower()) # 字母变成小写

3 . 格式字符串

name = input(‘请输入名字’)
age = int(input(‘请输入年龄’))
name = ‘小明’
age = 18
问题:写代码的时候可能会出现一个字符串中部分内容无法确定
xxx今年xx岁!
# 方法1:字符串拼接
str1 = name + '今年' + str(age) + '岁!'
print(str1)

# 方法2:格式占位符
str1 = '%s今年%d岁!' % (name, age)
print(str1)

# 方法3:使用f-string
str1 = f'{name}今年{age}岁!'
print(str1)
# 1.格式占位符创建字符串
语法:包含格式占位符的字符串 % (数据1,数据2,数据3…)
注意:后面括号中的数据必须和前面字符串的占位符一一对应
常用的格式占位符:
%s - 字符串占位符,可以对应任何类型的数据
%d - 整数占位符,可以对应任何数字
%f - 浮点数占位符,可以对应任何数字 保留6位小数
%.Nf - 保留N位小数
# xxx今年多少岁,月薪xxxx元!
str1 = '%s今年%d岁,月薪:%.2f元!' % (name, age, 10890)
print(str1)  # 小明今年18岁,月薪:10890.000000元!

nums = 34.8
str2 = '价格:%s' % nums
print(str2)  # 价格:34.8

str2 = '价格:%d' % nums
print(str2)  # 价格:34

str2 = '价格:%f' % nums
print(str2)  # 价格:34.800000

# 2.f-string
语法:在字符串最前面加f,就可以在字符串中通过‘{数据}’来提供字符串变化的部分
# 1)基本语法
names = '小明'
str1 = '{names}'
print(str1)  # {name}

str1 = f'{name}'
print(str1)  # 小明

str1 = f'{name * 2}'
print(str1)  # 小明小明

str1 = f'{name[1] * 3}'
print(str1)  # 明明明

str1 = f'{name}=={age + 10}'
print(str1)  # 小明==28

score = [90, 89, 67]
str1 = f'{name}三门学科分数:{score}'
print(str1)  # 小明三门学科分数:[90, 89, 67
2)加参数 : {表达式:参数}
1.控制小数位数的参数:{表达式:.Nf}
money = 17283
str1 = f'年薪:{money*13:.2f}元'
print(str1) # 年薪:224679.00元
2.显示百分比:{表达式:.N%} N代表保留多少为小数
rate = 0.87
str1 = f'班级及格率:{rate:.0%}'
print(str1) # 班级及格率:87%

3.逗号显示金额:{表达式:,}
1,000
18,234,567,200
money = 172830
str1 = f'年薪:{money*13:,}元'
print(str1)   # 年薪:2,246,790元

money = 172830
str1 = f'年薪:{money*13:,.2f}元'
print(str1)  # 年薪:2,246,790.00元

4.修改填充内容长度:{表达式:字符>长度}、{表达式:字符<长度}、{表达式:字符^长度}
nums  = 123
str1 = f'py2202{nums:0>5}'
print(str1)     # py220200003
str1 = f'py2202{nums:0<5}'
print(str1)     # py220230000
str1 = f'py2202{nums:0^5}'
print(str1)     # py220200300

作业

  1. 编写一个程序,交换指定字典的key和value。

      例如:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'}  
    dict1={'a':1, 'b':2, 'c':3}
    dict2 = {value : key for key,value in dict1.items()}
    print(dict2)
    
     
    
  2. 编写一个程序,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串

       例如: 传入'12a&bc12d-+'   -->  'abcd'  
    nums1 = '12a&bc12d-+'
    nums2 = ''
    for x in nums1:
        if 'a' <= x <= 'z':
            nums2 += x
    print(nums2)        
    
  3. 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母

      # 例如: 'abc' -> 'Abc'   '12asd'  --> '12asd'
        
    nums = input('请输入一串字符串:')
    nums1 = ''
    if 'a'<= nums[0] <='z':
        y  =  chr(ord(nums[0])-32)
        nums1 += y
    else:
        nums1 += nums[0]
    nums1 += nums[1:]
    print(nums1)
    
  4. 写程序实现endswith的功能,判断一个字符串是否已指定的字符串结束

       例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
            字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
    nums = 'abc231ab'
    nums1= 'bc23a'
    if nums1 in nums:
        print(True)
    else:
        print(False)                    
    
  5. 写程序实现isdigit的功能,判断一个字符串是否是纯数字字符串

       例如: '1234921'  结果: True
             '23函数'   结果: False
             'a2390'    结果: False
    nums = input('请输入一个字符串:')
    for x in nums:
        if '0'<= x <= '9':
            continue
        else:
            print('False')
            break
    else:
        print('True')  
    
  6. 写程序实现upper的功能,将一个字符串中所有的小写字母变成大写字母

        例如: 'abH23好rp1'   结果: 'ABH23好RP1'   
    nums ='abH23好rp1'
    nums1 = ''
    for x in nums:
        if 'a'<= x <='z':
            y  =  chr(ord(x)-32)
            nums1 += y
        else:
            nums1 += x
    print(nums1)            
    
  7. 写程序获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值

      例如: 序列:[-7, -12, -1, -9]    结果: -1   
           序列:'abcdpzasdz'    结果: 'z'  
           序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98}   结果: 98
                
    nums = [-7, -12, -1, -9]
    print(max(nums))
    nums1 = 'abcdpzasdz'
    print(max(nums1))
    
    nums2 = {'小明':90, '张三': 76, '路飞':30, '小花': 98}
    new_dict = {value: key for key, value in nums2.items()}
    nums3= list(new_dict)
    print(max(nums3))
    
    
  8. 写程序实现replace函数的功能,将指定字符串中指定的旧字符串转换成指定的新字符串

        例如: 原字符串: 'how are you? and you?'   旧字符串: 'you'  新字符串:'me'  结果: 'how are me? and me?
                            
     '
    
  9. 写程序实现split的功能,将字符串中指定子串作为切割点对字符串进行切割

    例如:原字符串: 'how are you? and you?'   切割点: 'you'  结果: ['how are ', '? and ', '?']
    
  10. 用思维导图总结四大容器:列表、字典、元组、集合

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值