Python-Basic Day-1 基本元素(数字、字符串)

一、数字

1.1 一个int型有多大

int类型变为可以存储任意大小的整数,甚至超过64位。Python在处理超大数计算方面不会产生任何错误,这是它的极大优势。

1.2 类型转换

我们可以方便地使用int()函数将其他的python数据类型转换为整型。

python 复制代码
>>> int(True)
1
>>> int(False)
0
>>> int(98.6)
98
>>> int(1.0e3)
1000
>>> int('123')
123

int()可以接受浮点数或由数字组成的字符串,但无法接受包含小数点或指数的字符串

python 复制代码
>>> int('98.6')
ValueError
>>> int('1.0e3')
ValueError

我们也可以通过float()str()进行浮点数与字符串的类型转换,略~

1.3 divmod函数

divmod()是Python的一个内置函数,它同时执行除法和取模运算,返回一个包含商和余数的元组。

python 复制代码
# 基本整数除法
result = divmod(10, 3)
print(result)        # 输出: (3, 1)
print(type(result))  # 输出: <class 'tuple'>

# 分解获取商和余数
quotient, remainder = divmod(17, 5)
print(f"商: {quotient}")      # 输出: 商: 3
print(f"余数: {remainder}")   # 输出: 余数: 2

二、字符串

2.1 使用 * 复制

在Python中,* 操作有复制序列的功能。

python 复制代码
# 使用 * 复制列表元素
original_list = [1, 2, 3]
copied_list = original_list * 3
print(copied_list)  # 输出: [1, 2, 3, 1, 2, 3, 1, 2, 3]

# 复制单个元素
single_element = ['hello'] * 5
print(single_element)  # 输出: ['hello', 'hello', 'hello', 'hello', 'hello']

# 使用 * 复制字符串
text = "Python "
repeated_text = text * 3
print(repeated_text)  # 输出: "Python Python Python "

char = "A"
repeated_char = char * 5
print(repeated_char)  # 输出: "AAAAA"

2.2 使用 start:end:step 分片

分片操作(slice)可以从一个字符串中抽取子字符串(字符串的一部分)。

  • :提取从开头到结尾的整个字符串
  • start: 从start 提取到结尾
  • :end 从开头提取到end - 1
  • start:end 从 start 提取到end - 1
  • start:end:step 从 start 提取到 end - 1,每 step 个字符提取一个
python 复制代码
# Python字符串分片(Slice)示例

# 定义示例字符串
s = "PythonProgrammingIsFun"

print("=== 基础分片 ===")
print(s[0:6])      # "Python"     [0到6)
print(s[6:17])     # "Programming" [6到17)
print(s[17:])      # "IsFun"      [17到末尾]
print(s[:6])       # "Python"     [开头到6)
print(s[-5:])      # "IsFun"      [倒数第5到末尾]
print(s[:-5])      # "PythonProgramming" [开头到倒数第5)
print(s[:])        # "PythonProgrammingIsFun" 完整复制

print("\n=== 步长分片 ===")
print(s[::2])      # "Pto rgamn sFn"  每隔1个取1个
print(s[1::2])     # "yhnPormigI u"   从索引1开始每隔1个取1个
print(s[::-1])     # "nuFsIgnimmargorPnohtyP" 字符串反转
print(s[17:6:-1])  # "sIgnimmargorP"  从索引17反向到索引6

print("\n=== 特殊情况 ===")
print(s[100:])     # ""           超出范围返回空字符串
print(s[-100:5])   # "Pytho"      负起点视为0
print(s[3:100])    # "honProgrammingIsFun" 负终点视为末尾

2.3 使用 split分割

split()是Python字符串处理中非常重要的方法,用于将字符串按指定分隔符分割成列表。

基本语法: str.split(sep=None, maxsplit=-1)

@params:

  • sep:分隔符,默认为None(使用空白字符作为分隔符)
  • maxsplit:最大分割次数,默认为-1(不限制分割次数)

@return: 返回分割后的字符串列表

python 复制代码
# 默认按空白字符(空格、制表符、换行符等)分割
text = "Hello World Python Programming"
result = text.split()
print(result)  # 输出: ['Hello', 'World', 'Python', 'Programming']

# 使用逗号分隔
csv_data = "apple,banana,orange,grape"
result = csv_data.split(',')
print(result)  # 输出: ['apple', 'banana', 'orange', 'grape']

2.4 使用 join 合并

join()是Python字符串处理中的一个方法,用于将序列中的元素连接成一个新的字符串。 join()的调用顺序看起来有点别扭,与 split() 相反,我们需要首先指定粘合用的字符串,然后再指定需要合并的列表:string. join(list)

python 复制代码
# 使用空字符串连接
chars = ['P', 'y', 't', 'h', 'o', 'n']
word = ''.join(chars)
print(word)  # 输出: 'Python'

# 创建CSV格式数据
items = ['apple', 'banana', 'orange', 'grape']
csv_data = ','.join(items)
print(csv_data)  # 输出: 'apple,banana,orange,grape'

# 创建路径
folders = ['usr', 'local', 'bin']
path = '/'.join(folders)
print(path)  # 输出: 'usr/local/bin'

2.5 使用 replace 替换

replace()是Python字符串处理中常用的方法,用于将字符串中的指定子串替换为新的子串。

python 复制代码
# 基本替换
text = "Hello World"
new_text = text.replace("World", "Python")
print(new_text)  # 输出: "Hello Python"
print(text)      # 输出: "Hello World" (原字符串不变)

# 替换单个字符
text = "apple"
new_text = text.replace("a", "A")
print(new_text)  # 输出: "Apple"

# 替换多个字符
text = "I like cats and cats like me"
new_text = text.replace("cats", "dogs")
print(new_text)  # 输出: "I like dogs and dogs like me"

# 替换空字符串(相当于插入)
text = "Hello"
new_text = text.replace("", " ")
print(new_text)  # 输出: " H e l l o "


text = "apple apple apple apple"
# 只替换前2次出现
result2 = text.replace("apple", "orange", 2)
print(result2)  # 输出: "orange orange apple apple"

2.6 其他常用字符串处理函数

find() - 查找子串第一次出现的位置

python 复制代码
# 基本语法:str.find(sub[, start[, end]])
text = "Hello World, Hello Python"

# 查找子串
pos1 = text.find("Hello")
print(pos1)  # 输出: 0

pos2 = text.find("World")
print(pos2)  # 输出: 6

# 查找不存在的子串
pos3 = text.find("Java")
print(pos3)  # 输出: -1

# 指定查找范围
pos4 = text.find("Hello", 5)  # 从索引5开始查找
print(pos4)  # 输出: 13

pos5 = text.find("Hello", 5, 10)  # 在索引5-10之间查找
print(pos5)  # 输出: -1 (没找到)

rfind() - 查找子串最后一次出现的位置

python 复制代码
text = "Hello World, Hello Python"

# 从右边开始查找
pos1 = text.rfind("Hello")
print(pos1)  # 输出: 13

pos2 = text.rfind("o")
print(pos2)  # 输出: 21

# 查找不存在的子串
pos3 = text.rfind("Java")
print(pos3)  # 输出: -1

# 实际应用:提取文件扩展名
filename = "document.backup.pdf"
dot_pos = filename.rfind(".")
if dot_pos != -1:
    extension = filename[dot_pos + 1:]
    print(f"文件扩展名: {extension}")  # 输出: 文件扩展名: pdf

count() 函数

python 复制代码
text = "apple banana apple cherry apple"

# 统计单词出现次数
count_apple = text.count("apple")
print(f"apple出现次数: {count_apple}")  # 输出: apple出现次数: 3

# 在指定范围内统计
count_range = text.count("apple", 10, 25)  # 在索引10-25之间
print(f"指定范围内apple出现次数: {count_range}")  # 输出: 指定范围内apple出现次数: 1

isalnum() 函数 - 检查字符串是否只包含字母和数字

python 复制代码
text1 = "Hello123"
print(text1.isalnum())  # 输出: True

text2 = "Hello World"
print(text2.isalnum())  # 输出: False (包含空格)

text3 = "Hello123!"
print(text3.isalnum())  # 输出: False (包含特殊字符)

# 超纲一下:实际应用
def sanitize_filename(filename):
    """清理文件名,移除非法字符"""
    # 只保留字母、数字、下划线和连字符
    cleaned = ''.join(c for c in filename if c.isalnum() or c in ('_', '-', '.'))
    return cleaned

startswith()endswith() 函数

startswith()函数

python 复制代码
# 基本语法:str.startswith(prefix[, start[, end]])
text = "Hello World"

# 检查开头
print(text.startswith("Hello"))  # 输出: True
print(text.startswith("World"))  # 输出: False
print(text.startswith("He"))     # 输出: True

# 检查多个可能的前缀
print(text.startswith(("Hello", "Hi", "Hey")))  # 输出: True

# 指定检查范围
print(text.startswith("World", 6))  # 输出: True (从索引6开始)
print(text.startswith("Wo", 6, 8))  # 输出: True (在索引6-8之间)

endswith()函数

python 复制代码
# 基本语法:str.endswith(suffix[, start[, end]])
text = "document.pdf"

# 检查结尾
print(text.endswith(".pdf"))     # 输出: True
print(text.endswith(".txt"))     # 输出: False
print(text.endswith("pdf"))      # 输出: True

# 检查多个可能的后缀
print(text.endswith((".pdf", ".doc", ".txt")))  # 输出: True

# 指定检查范围
print(text.endswith("men", 0, 8))  # 输出: True (在索引0-8之间)
相关推荐
不如语冰18 分钟前
AI大模型入门-pytorch-张量2 tensor创建
python
NPE~30 分钟前
[AI]Agent开发——ADK框架使用
人工智能·python·ai·教程·adk·agent开发
矮个史蒂芬32 分钟前
统计verilog .v文件中output 的bit数
python
gwf2161 小时前
磨损均衡算法(Wear Leveling)——SSD如何让每块闪存“公平退休“?
运维·数据库·人工智能·python·嵌入式硬件·算法·智能硬件
爱吃提升1 小时前
python 分布式爬虫、爬虫合规与综合实战项目
分布式·爬虫·python
审小匠OpenCPAi1 小时前
银行流水核查怎么自动化?单边匹配、双向勾稽与图聚类异常检测的工程对比
java·前端·人工智能·python·审计
元Y亨H2 小时前
Pandas 解析 Excel 导致的内存溢出(MemoryError)
python·excel
金銀銅鐵3 小时前
[Python] 用 turtle 来绘制瑞典国旗
python
Albert Edison3 小时前
【GUI 自动化测试】Pywinauto 常见操作
自动化测试·python·pywinauto
海兰3 小时前
【高速缓存】RedisVL为文本生成嵌入向量实践指南
人工智能·python·机器学习