Python自学第5天:字符串相关操作

1.字符串运算符

作符描述
+字符串连接
*重复输出字符串
[]通过索引获取字符串中字符
[ : ]截取字符串中的一部分,遵循左闭右开原则,str[0:2] 是不包含第 3 个字符的。
in成员运算符 - 如果字符串中包含给定的字符返回 True
not in成员运算符 - 如果字符串中不包含给定的字符返回 True
# 字符串连接
str1 = "Hello"
str2 = "World"
result = str1 + str2  # 输出: HelloWorld

# 字符串重复
str3 = "Ha"
result = str3 * 3  # 输出: HaHaHa

# 字符串索引
text = "Python"
char = text[0]  # 输出: P

# 字符串切片
text = "Python Programming"
slice_str = text[0:6]  # 输出: Python

# 成员运算符
text = "Hello Python"
print("Hello" in text)  # 输出: True
print("Java" not in text)  # 输出: True

 2.字符串格式化

作符描述
      %c 格式化字符及其ASCII码
      %s 格式化字符串
      %d 格式化整数
      %o 格式化无符号八进制数
      %x 格式化无符号十六进制数
      %f 格式化浮点数字,可指定小数点后的精度
      %e 用科学计数法格式化浮点数
name = "张三"
age = 25
height = 1.75

# %s 字符串格式化
print("姓名: %s" % name)  # 输出: 姓名: 张三

# %d 整数格式化
print("年龄: %d岁" % age)  # 输出: 年龄: 25岁

# %f 浮点数格式化
print("身高: %.2f米" % height)  # 输出: 身高: 1.75米

# 多个变量格式化
print("个人信息 - 姓名: %s, 年龄: %d岁, 身高: %.2f米" % (name, age, height))

# 其他格式化示例
num = 42
print("十六进制: %x" % num)  # 输出: 十六进制: 2a
print("八进制: %o" % num)    # 输出: 八进制: 52
print("科学计数: %e" % 1234.5678)  # 输出: 科学计数: 1.234568e+03

3.f-string

  • 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去。
  • 比起上述格式化方法个,更简洁,不用再去判断类型。
name = "李四"
age = 30
score = 98.5

# 基本用法
print(f"姓名: {name}")  # 输出: 姓名: 李四
print(f"年龄: {age}岁")  # 输出: 年龄: 30岁
print(f"成绩: {score}分")  # 输出: 成绩: 98.5分

# 表达式计算
x = 10
y = 20
print(f"{x} + {y} = {x + y}")  # 输出: 10 + 20 = 30

# 调用函数
def get_square(n):
    return n * n
number = 8
print(f"{number}的平方是{get_square(number)}")  # 输出: 8的平方是64

# 字典访问
student = {"name": "王五", "grade": "A"}
print(f"学生{student['name']}的等级是{student['grade']}")  # 输出: 学生王五的等级是A

# 对齐和填充
print(f"{'左对齐':<10}|")  # 输出: 左对齐    |
print(f"{'右对齐':>10}|")  # 输出:     右对齐|
print(f"{'居中':^10}|")    # 输出:    居中   |

# 进制转换
num = 42
print(f"十进制: {num}")         # 输出: 十进制: 42
print(f"二进制: {num:b}")       # 输出: 二进制: 101010
print(f"十六进制: {num:x}")     # 输出: 十六进制: 2a

4.字符串常用的内置函数

作符描述
len() 获取字符串长度
upper() 转化为大写
lower() 转化为小写
strip() 去除首尾空白字符
split() 字符串分割
join() 字符串连接
replace() 字符串替换
find() 和 index() 字符串查找子串
startswith(str)判断字符串是否以str开头
endswith(str)判断字符串是否以str结尾
count()统计子串出现次数
isdigit()是否是数字

isalpha()

是否是字母
isalnum是否为字母或数字
# len() - 获取字符串长度
text = "Python编程"
print(f"字符串长度: {len(text)}")  # 输出: 字符串长度: 7

# upper() 和 lower() - 大小写转换
str1 = "Hello World"
print(f"转大写: {str1.upper()}")  # 输出: HELLO WORLD
print(f"转小写: {str1.lower()}")  # 输出: hello world

# strip() - 去除首尾空白字符
str2 = "   Python   "
print(f"去除空白: '{str2.strip()}'")  # 输出: 'Python'

# split() - 字符串分割
str3 = "Python,Java,C++"
print(f"分割结果: {str3.split(',')}")  # 输出: ['Python', 'Java', 'C++']

# join() - 字符串连接
list1 = ['Python', 'Java', 'C++']
print(f"连接结果: {'-'.join(list1)}")  # 输出: Python-Java-C++

# replace() - 字符串替换
str4 = "Hello Python Python"
print(f"替换结果: {str4.replace('Python', 'Java', 1)}")  # 输出: Hello Java Python

# find() 和 index() - 查找子串
str5 = "Hello Python"
print(f"find查找: {str5.find('Python')}")  # 输出: 6
print(f"index查找: {str5.index('Python')}")  # 输出: 6

# startswith() 和 endswith() - 判断开头和结尾
str6 = "test.py"
print(f"是否以test开头: {str6.startswith('test')}")  # 输出: True
print(f"是否以.py结尾: {str6.endswith('.py')}")  # 输出: True

# count() - 统计子串出现次数
str7 = "Python Python Python"
print(f"Python出现次数: {str7.count('Python')}")  # 输出: 3

# isdigit()、isalpha()、isalnum() - 字符串类型判断
str8 = "123"
str9 = "abc"
str10 = "abc123"
print(f"是否为数字: {str8.isdigit()}")  # 输出: True
print(f"是否为字母: {str9.isalpha()}")  # 输出: True
print(f"是否为字母或数字: {str10.isalnum()}")  # 输出: True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ghost143

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值