Python_字符串的基本使用

本文深入讲解了Python中字符串的各种操作,包括定义与遍历、统计操作、查找与替换、文本对齐及拆分与合并等。通过实例演示了如何利用Python内置函数进行字符串处理,适合初学者和进阶学习者。
# 字符串定义和遍历
str1 = "hello python"
str2 = "我的名字是“good"

print(str2)
print(str1[6])

for char in str2:
    print(char)
# 字符串统计操作
str1 = "hello python"

# 1. 统计字符串长度
print(len(str1))

#2. 统计某一个子字符串出现的次数
print(str1.count('llo'))
print(str1.count('abc'))

#3. 某一个字符串出现的位置
print(str1.index("llo"))
# 1. 判断空白字符
space_str = "      \t\n\r"

print(space_str.isspace())

# 2. 判断字符串中是否只包含数字
# 1> 都不能判断小数
# num_str = "1.1"
# 2> unicode 字符串
# num_str = "\u00b2"
# 3> 中文数字
num_str = "一千零一"

print(num_str)
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())

#字符串的查找替换

hello_str = "hello world"

# 1. 判断是否以指定字符串开始
print(hello_str.startswith("Hello"))

# 2. 判断是否以指定字符串结束
print(hello_str.endswith("world"))

# 3. 查找指定字符串
# index同样可以查找指定的字符串在大字符串中的索引
print(hello_str.find("llo"))
# index如果指定的字符串不存在,会报错
# find如果指定的字符串不存在,会返回-1
print(hello_str.find("abc"))

# 4. 替换字符串
# replace方法执行完成之后,会返回一个新的字符串
# 注意:不会修改原有字符串的内容
print(hello_str.replace("world", "python"))

print(hello_str)

#字符串文本的对其

# 假设:以下内容是从网络上抓取的
# 要求:顺序并且居中对齐输出以下内容
poem = ["\t\n登鹳雀楼",
         "王之涣",
         "白日依山尽\t\n",
         "黄河入海流",
         "欲穷千里目",
         "更上一层楼"]

for poem_str in poem:

    # 先使用strip方法去除字符串中的空白字符
    # 再使用center方法居中显示文本
    print("|%s|" % poem_str.strip().center(10, " "))

# 字符串文本对其

# 要求:
# 1. 将字符串中的空白字符全部去掉
# 2. 再使用 " " 作为分隔符,拼接成一个整齐的字符串
poem_str = "登鹳雀楼\t 王之涣 \t 白日依山尽 \t \n 黄河入海流 \t\t 欲穷千里目 \t\t\n更上一层楼"

print(poem_str)

# 1. 拆分字符串
poem_list = poem_str.split()
print(poem_list)

# 2. 合并字符串
result = " ".join(poem_list)
print(result)




#摘自黑马
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值