小白自嗨之python字符串

1、字符串的定义

字符串是 Python 中最常用的数据类型。我们可以通常使用引号( ' 或 " )来创建字符串,三引号也可以

s0 = "hello world"
s1 = 'hello world'
# '''''' 多用于程序开头注释文档
s2 = """hello world"""
s3 = '''hello world'''

2、字符串的遍历

1.单个字符遍历

s12 = "中华人民共和国台湾省"
for c in s12:
    print(c)

结果

2.根据索引遍历

s12 = "中华人民共和国台湾省"
for i in range(len(s12)):
    print(i, s12[i])

结果如下:

3、字符串的常见操作

1.将字母全转为大写

s = " abc dfs Bfe sfG"
print(s.upper())

结果如下

2.将字母全转为小写

s = " abc dfs Bfe sfG"
print(s.lower())

3.将字符串单词首字母大写

s = " abc dfs Bfe sfG"
print(s.title())

4.将字符串首字母大写

s = "abc dfs Bfe sfG"
print(s.capitalize())

5.字符查找inde()or  rindex()找不到报错

s = "abc dfs Bfe sfG"
print(s.index("B"))

6.字符查找find()or rfind()找不到返回-1

s = "abc dfs Bfe sfG"
print(s.find("B"))

7.字符填充center()30字符居中

s = "abc dfs Bfe sfG"
print(s.center(30, "+"))

8.rjust()向右填充,ljust()向左填充类似center()

9、zfill()向左填充0

print("中国".zfill(20))

10.startswith()是否以字符串开始 endswith()是否以该字符结束,返回布尔值

s1 = "hello world"
print(s1.startswith("h"))
print(s1.endswith("d"))

11.split()分割字符串,默认以空格分割

s1 = "hello world"
print(s1.split())

12.大小写颠倒

print("Asdfsac".swapcase())

13.替换字符

s = "abc dfs Bfe sfG"
print(s.replace("a", "A"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值