Python字符串

Python学习之路,点击有全套Python笔记

1、字符串索引
name = '123456'
print(name[0])
print(name[1])
print(name[2])
2、字符串切片序列[开始位置下标:结束位置下标:步⻓] [,)
name = "abcdefg"
print(name[2:5:1]) # cde
print(name[2:5]) # cde
print(name[:5]) # abcde
print(name[1:]) # bcdefg
print(name[:]) # abcdefg
print(name[::2]) # aceg
print(name[:-1]) # abcdef, 负1表示倒数第一个数据
print(name[-4:-1]) # def
print(name[::-1]) # gfedcba
3、查找
str1 = "hello and world and puber and python"

# find  字符串序列.find(子串, 开始位置下标, 结束位置下标),没有就返回-1
print(str1.find('and')) # 6
print(str1.find('and', 8, 20))  # 16
print(str1.find('add'))  # -1

# index  字符串序列.find(子串, 开始位置下标, 结束位置下标),没有就报错
print(str1.index('ands'))

# count 字符串序列.count(⼦子串, 开始位置下标, 结束位置下标)
print(str1.count('and'))  # 3
4、修改
# 修改
# repalce 替换,返回新的字符串,原有字符串不改变
# 字符串序列.replace(旧⼦子串, 新⼦子串, 替换次数)
str1 = "hello and world and puber and python"
str2 = str1.replace('and', 'he')
print(str2)
str3 = str1.replace('and', 'he', 2) # hello he world he puber and python
print(str3)
str4 = str1.replace('and', 'he', 5) # hello he world he puber he python
print(str4)
# split 分割,字符串序列.split(分割字符, num)
# num表示的是分割字符出现的次数,即将来返回数据个数为num+1个
print(str1.split('and'))
print(str1.split('and', 2))
print(str1.split(" "))

# 合并 + join() 字符或子串.join(多字符串组成的序列)
first_name = 'jack'
last_name = 'boss'
print(first_name + " " +last_name)  # jack boss
print('.'.join(first_name))  # j.a.c.k

# 大小写转换
# title 将首字母大写
print(first_name.title())
# upper 全部大写
new_name = first_name.upper()
print(new_name)
# lower 全部小写
print(new_name.lower())
# 添加空白符 \t:制表符,一个tab的距离
print("\thello")
# 添加换行符 \n:换行
print("hello\nworld\n")

# 删除空白
# strip 删除左右空白
H = '     hello    '
print(H.strip())
# lstrip 删除左侧空白
print(H.lstrip())
# rstrip 删除右侧空白
print(H.rstrip())
# 判断

# startswith():检查字符串是否是以指定⼦串开头,返回bool值
# 字符串序列.startswith(⼦串, 开始位置下标, 结束位置下标)
new_str1 = str1 + '123'
print(new_str1.startswith('hello'))
print(new_str1.startswith('hello', 5, 10))

# endswith():检查字符串是否是以指定⼦串开头,返回bool值
# 字符串序列.endswith(⼦串, 开始位置下标, 结束位置下标)
print(str1.endswith('python'))
print(str1.endswith('python', 4, 5))

# isalpha():如果字符串⾄至少有⼀个字符并且所有字符都是字⺟,返回bool值
print(first_name.isalpha())
print(new_str1.isalpha())

# isdigit():如果字符串⾄至少有⼀个字符并且所有字符都是数字,返回bool值
num = '123'
print(num.isdigit())

# isalnum():如果字符串⾄至少有一个字符并且所有字符都是字母或数字,返回bool值
print(new_str1.isalnum())
print(num.isalnum())

# isspace():如果字符串中只包含空⽩,返回bool值
print(new_str1.isspace())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值