Python 字符串的基本操作

这篇博客详细介绍了Python中字符串的基本操作,包括字符串截取、去空格、复制、连接、计算长度、查找最大最小字符、转换、分割、序列连接、查找与替换以及特定字符判断等核心功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python 字符串的基本操作

字符串

#字符串截取

s = "hello"
#格式 [起点:终点]   数字为下角标   取0不去3(0,1,2)
#截取中间字符
print(s[0:3])
#截取全部字符
print(s[:])
s = "hello"
#格式 [起点:终点:步长]
#截取字符的长度为2
print(s[::2])
#取反
print(s[::-1])

#去空格(去左右空格)

s = "    hello    "
#去两边空格
print(s.strip())
#去左边空格
print(s.lstrip())
#去右边空格
print(s.rstrip())
#字符串

#字符串复制

s = "hello"
s_copy = s

#字符串连接

s = "hello"
s1 = "python"
s2 = s + s1
print(s2)
#另一种拼接方式
#lt(a, b) ———— 小于
#le(a, b) ———— 小于等于
#eq(a, b) ———— 等于
#ne(a, b) ———— 不等于
#ge(a, b) ———— 大于等于
#gt(a, b) ———— 大于
s = "hello"
s1 = "python"
import operator
s2 = operator.concat(s,s1)
print(s2)
s = "hello"
s1 = "python"
#调用operator库中的lt函数   
#lt函数是按照ASCⅡ码从头开始比较两个字符串大小   返回值为bool类型(True Flase)
b = operator.lt(s,s1)
print(b)
print(s<s1)

#字符串长度

s = "hello"
s1 = "python"
print(len(s),len(s1))

#字符串最大字符,最小字符

s = "hello"
print(max(s))
print(min(s))

#字符串转换

#upper ———— 转换为大写
#lower ———— 转换为小写
#title ———— 转换为标题(每个单词首字母大写)
#capitalize ———— 首字母大写
#swapcase ———— 大写变小写,小写变大写
#大写转小写
print(s.upper())
#小写转大写
print(s.lower())
#每个字母的首字母大写
print(s.title())
#第一个字母的首字母大写
print(s.capitalize())
#注:capitalize(): 字符串第一个字母大写   title():字符串内的所有单词的首字母大写
#大小写转换(大写转小写 小写转大写)
print(s.swapcase())

#字符串分割

#不写参数 默认按空格分割成列表
s = "hqelASD how are you"
ss = s.split()
print(ss)
#按照参数o分割成列表
s = "hqelASD how are you"
ss = s.split("o")
print(ss)

#字符串序列连接

#把s1中每个元素按顺序连接在s的最前面
s = "hqelASD how are you"
s1 = "123"
s2 = s.join(s1)
print(s2)

#字符串内查找

#find查找下标
s1 = "today is a fine day is"
#查找到的第一个
index = s1.find("is")
print(index)
#在下表5 8之内查找
index0 = s1.find("is",5,8)
print(index0)

#字符串内替换

s1 = "today is a fine day is"
#参数 old new count
#格式 replace(要替换的,替换成,替换前几个)
s = s1.replace("is","are",500)
print(s,s1)

#字符串判断

#isdigit ———— 检测字符串时候只由数字组成
#isalnum ———— 检测字符串是否只由数字和字母组成
#isalpha ———— 检测字符串是否只由字母组成
#islower ———— 检测字符串是否只含有小写字母
#isupper ———— 检测字符串是否只含有大写字母
#isspace ———— 检测字符串是否只含有空格
#istitle ———— 检测字符串是否是标题(每个单词首字母大写)
s = " d "
print(s.isspace())

#取出所有的to

s = """
Variables are used to store information to be referenced and manipulated in a computer program.
They also provide a way of labeling data with a descriptive name, so our programs can be understood 
more clearly by the reader and ourselves. It is helpful to think of variables as containers that 
hold information. Their sole purpose is to label and store data in memory. This data can then be 
used throughout your program.
"""
#取出所有to
c = s.find("to")
while c!=-1:
    print(s[c:c+2])
    c = s.find("to",c+2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值