Python学习:字符串类型,包括常用操作,常用方法和字符串的切片示例

hello_str = "hello hello"

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

# 2. 统计子串出现的次数
print(hello_str.count("llo"))
print(hello_str.count("abc"))  # 不报错,显示0,说明没有该子串

# 3. 某子串出现的位置 字符串.index("子串")
print(hello_str.index("llo"))  # 回显2 是取的第一个hello中的第一个l的位置
# print(hello_str.index("abc"))#不存在abc子串,程序报错


# 常用方法示例:

# 1.判断空白字符
space_str = "\t \n \r "
print(space_str.isspace())  # 回显True

# 2.判断是否只包含数字
num_str = "1"
print(num_str.isdecimal())  # decimal十进制,常用
print(num_str.isdigit())
print(num_str.isnumeric())
# 连续输出三行True
# 但如果改num_str="1.1"会显示三行False,这三者都不能判断小数为数字

num_str = "\u00b2"  # unicode字符串,平方字符
print(num_str)
print(num_str.isdecimal())  # decimal十进制,返回False
print(num_str.isdigit())  # 返回True
print(num_str.isnumeric())  # 返回True

num_str = "一千"  # 中文数字
print(num_str)
print(num_str.isdecimal())  # decimal十进制,返回False
print(num_str.isdigit())  # 返回False
print(num_str.isnumeric())  # 返回True,骚的,能判断中文数字

# 3.查找和替换
# 判断是否以指定的字符串开始/结束 字符串.startswith("hello")
hello_str = "hello hello"
print(hello_str.startswith("hello"))  # True
print(hello_str.endswith("world"))  # False]

# 查找指定字符串
print(hello_str.find("llo"))  # 返回第一个llo的索引位置,若不存在返回-1
# 与index方法对比:find方法若指定字符串不存在会返回-1
# index方法会报错

# 替换指定字符串(不改变原来的字符串)
print(hello_str.replace("hello", "python"))  # 打印两个hello都替换为python
print(hello_str)  # 但不改变原来的字符串!!!!!

# 4.文本对齐
# 假设该数据从网络上抓取,想给他排列格式
poem = ["登鹳雀楼",
        "王之涣",
        "白日依山尽",
        "黄河入海流",
        "欲穷千里目",
        "更上一层楼"]
for poem_str in poem:
    print("|%s|" % poem_str.center(10, " "))  # 居中
for poem_str in poem:
    print("|%s|" % poem_str.ljust(10, " "))  # 左对齐,l改为r是右对齐

# 5.去除空白字符strip
# 假设该数据从网络上抓取,想给他排列格式
poem = ["\t\n登鹳雀楼",
        "王之涣",
        "白日依山尽\t\n",
        "黄河入海流",
        "欲穷千里目",
        "更上一层楼"]
for poem_str in poem:  # 不整齐文档输出与下面对比
    print("|%s|" % poem_str.center(10, " "))
for poem_str in poem:
    # 只需在居中对齐之前加上strip方法去除空白格式即可
    print("|%s|" % poem_str.strip().center(10, " "))  # 居中

# 6.拆分和连接split拆分,join连接
# 假设该数据从网络上抓取,想给他排列格式
poem_str2 = "\t\n登鹳雀楼 \t王之涣\t \n白日依山尽\t\n 黄河入海流\t 欲穷千里目\t 更上一层楼"
print(poem_str2)
# 拆分
poem_list = poem_str2.split()
print(poem_list)
# 合并
# 要求使用空格作为分隔符,拼接成一个整齐的字符,用空格调用join方法
result = " ".join(poem_list)
print(result)



#关于"字符串的切片"
num_str="0123456789"
print(num_str[2:6])#2~5位置
print(num_str[2:])#2~末尾
print(num_str[:6])#开头~5位置
print(num_str[:])#截取完整字符串

print(num_str[::2])#从开始位置每隔一个字符截取字符串,步长为2
print(num_str[2:-1])#截取从2到 末尾-1 的位置的字符
print(num_str[-2:])#截取末尾两个字符
print(num_str[-1::-1])#逆序截取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值