首页 Python基础入门视频教程 Python字符串转换方法(eval() 、capitalize()、title() 、lower() 、upper() 、swapcase() 、encode() 、decode())详解
pay pay

Python字符串转换方法(eval() 、capitalize()、title() 、lower() 、upper() 、swapcase() 、encode() 、decode())详解

日期: 二月 14, 2023, 7:11 a.m.
阅读: 651
作者: Python自学网-村长

摘要: Python字符串转换方法(eval() 、capitalize()、title() 、lower() 、upper() 、swapcase() 、encode() 、decode())详解

str5 = 'python is a easy programming language'
str7 = 'Python is a easy Programming Language'

1.eval() 把字符串转成数值类型并计算返回值

num = eval('6543')
print(num)
print(type(num))
print(eval('+6556'))
print(eval('-6556'))
print(eval('65-56'))  # int函数不能这样
print(eval('65+56'))
# print(eval('65n56'))

2.capitalize() 首字母改大写,其他小写

print(str7.capitalize())

3.title() 每个单词首字母大写

print(str7.title())

4.lower() 把字符串中的大写字母转成小写

print(str7.lower())
注意:下面两种函数调用方法的区别
str7.lower()  # 这种是调用类中的方法,也就是对象方法,一般用已经封装的方法,面向对象中细说:class str(object):中方法
len(str5)  # 这种是使用内建方法:builtins模块直接创建的方法,对比看缩进

5.upper() 把字符串中的小写字母转成大写

print(str7.upper())

6.swapcase() 把字符串中的大写该小写,小写改大写

print(str7.swapcase())

7.encode()  # 转码

print(str7.encode('GBK', 'strict'))  # 返回结果:b'Python is a easy Programming Language'
print(type(str7.encode('utf-8', 'strict')))  # 返回结果:<class 'bytes'>

8.decode()  # 解码

str77 = str7.encode('GBK', 'strict')  # 使用转码后的bytes类型字符串
print(str77.decode('utf-8', 'strict'))  # 返回结果:<class 'str'>
print(type(str77.decode('utf-8', 'strict')))

 

原创视频,版权所有,未经允许,切勿转载,违者必究!
回顶部