boolean_result1 = bool(string_value) # True
print(boolean_result1)
list_value = []
boolean_result2 = bool(list_value) # False
print(boolean_result2)
将布尔值转换为整数
true_value = True
integer_result1 = int(true_value) # 1
print(integer_result1)
false_value = False
integer_result2 = int(false_value) # 0
print(integer_result2)
输出结果为:
True
False
1
0
**复数,整数及浮点数**之间的转换举例:
将整数转换为复数
num = 5
complex_num = complex(num)
print(complex_num) # (5+0j)
将浮点数转换为复数
num = 3.14
complex_num = complex(num)
print(complex_num) # (3.14+0j)
将复数转换为整数
complex_num = 7 + 8j
integer_part = int(complex_num.real)
print(integer_part) # 7
将复数转换为浮点数
complex_num = 9 - 6j
floating_point_part = float(complex_num.real)
print(floating_point_part) # 9.0
**日期和时间的转换**使用内置模块datetime来转换:
1. 将字符串类型的日期或时间转换为datetime对象:
from datetime import datetime
date_str = “2024-01-08”
time_str = “14:30:00”
date_obj = datetime.strptime(date_str, “%Y-%m-%d”)
time_obj = datetime.strptime(time_str, “%H:%M:%S”)
print(“Date Object:”, date_obj)
print(“Time Object:”, time_obj)
>
> 输出结果为:
>
>
> Date Object: 2024-01-08 00:00:00
> Time Object: 1900-01-01 14:30:00
>
>
>
2.将datetime对象格式化成指定的字符串形式:
formatted_date = date_obj.strftime(“%Y年%m月%d日”)
formatted_time = time_obj.strftime(“%H点%M分%S秒”)
print(“Formatted Date:”, formatted_date)
print(“Formatted Time:”, formatted_time)
>
> 输出结果为:
>
>
> Formatted Date: 2024年01月08日
> Formatted Time: 14点30分00秒
>
>
>
对于Excel表格中的数据,可以使用Python的**pandas库**来读取和处理数据:
以下是将Excel表格中的数据转换为指定数据类型的示例代码:
import pandas as pd
读取Excel表格数据
感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的:
① 2000多本Python电子书(主流和经典的书籍应该都有了)
② Python标准库资料(最全中文版)
③ 项目源码(四五十个有趣且经典的练手项目及源码)
④ Python基础入门、爬虫、web开发、大数据分析方面的视频(适合小白学习)
⑤ Python学习路线图(告别不入流的学习)
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!