Python基础:字符串
1、三引号:支持回车换行
# 三引号
a = """I
am TOM"""
print(a)
2、下标
a = """I
am TOM"""
for i in range(len(a)):
print(a[i])
3、切片
序列[beg🔚stepsize]
a = "012345678"
print(a[2:5]) # 234
print(a[2:6:2]) # 24
print(a[:6]) # 012345
print(a[3::2]) # 357
print(a[::-1]) # 876543210
print(a[::-2]) # 86420
print(a[-4:-1]) # 567
print(a[-4:-1:-1]) # 不能选出数据
print(a[-1:-4:-1]) # 876
4、查找
mystr = "hello world and itcast and itheima and Python"
print(mystr.find("and", 15, len(mystr))) # 23
print(mystr.find("ands")) # -1
print(mystr.index('and')) # 12
# print(mystr.index('ands')) # 报错
print(mystr.count('and', 15, len(mystr))) # 2
print(mystr.count('ands')) # 0
print(mystr.rfind("and")) # 35
print(mystr.rfind("ands")) # -1
print(mystr.rindex("and")) # 35
# print(mystr.rindex("ands")) # 报错
5、替换
mystr = "hello world and itcast and itheima and Python"
print(mystr) # hello world and itcast and itheima and Python
new_str = mystr.replace('and', 'AND') # 字符串是不可变类型
print(new_str) # hello world AND itcast AND itheima AND Python
new_str = mystr.replace('and', 'AND', 1) # 字符串是不可变类型
print(new_str) # hello world AND itcast and itheima and Python
6、分割
mystr = "hello world and itcast and itheima and Python"
list1 = mystr.split('and')
print(list1) # ['hello world ', ' itcast ', ' itheima ', ' Python']
list2 = mystr.split(' ')
print(list2) # ['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
list3 = mystr.split(' ', 2)
print(list3) # ['hello', 'world', 'and itcast and itheima and Python']
7、合并列表数据为字符串
my_list = ['aa', 'bb', 'cc']
my_str = '...'.join(my_list)
print(my_str) # aa...bb...cc
8、大小写转换
my_str = "hello world PYthon"
print(my_str.capitalize()) # Hello world python
print(my_str.title()) # Hello World Python
print(my_str.upper()) # HELLO WORLD PYTHON
print(my_str.lower()) # hello world python
9、删除空白字符
my_str = " hello world PYthon "
print(my_str.lstrip()) # "hello world PYthon "
print(my_str.rstrip()) # " hello world PYthon"
print(my_str.strip()) # "hello world PYthon"
10、字符串对齐
my_str = "hello"
print(my_str.ljust(10, '.')) # hello.....
print(my_str.rjust(10, '*')) # *****hello
print(my_str.center(11, '$')) # $$$hello$$$
11、判断
判断字符串是否以某字符串开头/结尾
my_str = "hello"
print(my_str.startswith('he')) # True
print(my_str.endswith('o')) # True
print(my_str.endswith('e')) # False
判断字符串是否为数字/字母
my_str1 = "hello"
print(my_str1.isalpha())
my_str2 = "01234"
print(my_str2.isdigit())
my_str3 = "hello world"
print(my_str3.isalpha()) # False
my_str4 = "hello12345"
print(my_str4.isalnum())
my_str5 = " "
print(my_str5.isspace())