Python基础:字符串

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())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值