Python字符串操作方法详解

python 字符串常用方法

  • 创建字符串:s = "Hello, World!"
  • 字符串索引和切片
# 索引和切片  
print(s[0])  # 输出: H (索引第一个字符)  
print(s[7])  # 输出: , (索引第八个字符)  
print(s[1:5])  # 输出: ell (切片从索引1到4的子串)  
  • find() 和 index():查找子串在字符串中的位置(返回索引),如果找不到则返回-1(但index()方法会抛出异常)
s = "Hello, World!"  
print(s.find("World"))  # 输出: 7  
print(s.index("World")) # 输出: 7  
# 如果找不到子串,find()返回-1,而index()会抛出ValueError异常
  • len():返回字符串的长度(字符数)print(len(s)) # 输出: 13
  • 连接字符串 (加法),字符串乘法
# 连接字符串  
s2 = "Python"  
print(s + " " + s2)  # 输出: Hello, World! Python 
# 字符串乘法 ,无缝连接
print(s2 * 3)  # 输出: PythonPythonPython  
  • join():将序列中的元素以指定的字符连接生成一个新的字符串
list_of_fruits = ["apple", "banana", "cherry"]  # 序列
# 将序列中的元素以指定的字符‘,’连接生成一个新的字符串
s = ", ".join(list_of_fruits)  
print(s)  # 输出: apple, banana, cherry
  • lower() 和 upper():分别将字符串转换为小写和大写
# 分别将字符串转换为小写和大写
s = "Hello, World!"  
print(s.lower())  # 输出: hello, world!  
print(s.upper())  # 输出: HELLO, WORLD!
  • strip(), lstrip(), rstrip():去除字符串两端的空白(或其他指定字符)
    //strip=n队服,v除去…外皮。L、R左右。
# 去除字符串两端的空白  
print(s.strip())  # 输出: Hello, World! (如果字符串两端有空格,它们会被去除)  
  • split():将字符串分割成子字符串列表,并返回该列表
# 字符串分割  
print(s.split(","))  # 输出: ['Hello', ' World!'] (以逗号分割字符串)  
  • replace():替换字符串中的子串
# 字符串替换  
print(s.replace("World", "Python"))  # 输出: Hello, Python!  
  • startswith() 和 endswith():检查字符串是否以指定的前缀或后缀开始或结束,返回True或False
s = "Hello, World!"  
print(s.startswith("Hello"))  # 输出: True  
print(s.endswith("!"))       # 输出: True
  • format()(或f-string):格式化字符串
name = "Ralan"  
age = 6  
print("My name is {} and I am {} years old.".format(name, age))  # 输出: My name is Ralanand I am 6 years old.  
print(f"My name is {name} and I am {age} years old.")  # 输出: My name is Ralanand I am 6 years old.
  • isalpha(), isdigit(), isalnum(),isspace():检查字符串是否全部由字母、数字或字母数字字符组成,返回True或False
s1 = "Hello"  
s2 = "123"  
s3 = "Hello123"  
print(s1.isalpha())  # 输出: True  
print(s2.isdigit())  # 输出: True  
# alpha and num=alnum
print(s3.isalnum())  # 输出: True  
print(s1.isspace())  # 输出: False (因为不包含空格字符或只由空格字符组成)
  • 字符串的编码和解码
encoded = s.encode('utf-8')  # 编码为字节串  
print(encoded)  # 输出: b'Hello, World!'  
decoded = encoded.decode('utf-8')  # 解码回字符串  
print(decoded)  # 输出: Hello, World!  

python字符串内置方法。
关注收藏,多浏览,便于使用。

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏常青

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值