7天玩转Python(四)Python字符串

本文围绕Python字符串操作展开,介绍了字符串格式化的语法及对齐、去转义符操作;阐述了用“+”和join()函数合并字符串;说明了通过索引、切片、split()截取子串;还提及字符串比较、反转,以及用find()查找、replace()替换字符串等内容。

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

字符串的格式化

字符串格式化的语法:“s%”%str1

                                         "s%s%"%(str1,str2)

str1 = "version"
num = 1
print("str:%s" % str1)
print("num:%d str1:%s" % (num, str1))

字符串对其操作

word = "version3.0"
print(word.center(20))               #变量两侧输出5个空格
print(word.center(20, "*"))          #变量两侧各输出5个*
print(word.ljust(0))                 #输出结果左对齐
print(word.rjust(20))                #输出20个字符,左边占10个空格

去字符串的转义符

word = "\thello world\n"
print("直接输出:", word)
print("strip()", word.strip())     #去除转义字符
print("lstrip()", word.lstrip())   #去除左转义字符
print("rstrip()", word.rstrip())   #去除右转义字符

字符串的合并

python使用“+”连接字符串,python会根据“+”两侧的类型,决定执行连接操作或加法运算。如果两侧都是字符串执行连接操作;如果两侧都是数字类型则执行加法运算,两侧不同的类型,将抛出异常。

str1 = "hello"
str2 = "python"
result = str1+str2
print(result)

python还提供了join()函数进行字符串的合并

strs = ['hello',"python"]
print(" ".join(strs))

字符串的截取

使用索引截取子串

word = "python"
print(word[4])

特殊切片截取子串

s1 = 'hello python'
print(s1[0:3])
print(s1[::2])
print(s1[1::2])

split()获取子串

sentence = "Bob said:1,2,3,4"
print(sentence.split())         #空格截取子串
print(sentence.split(","))      #逗号截取子串
print(sentence.split(",", 2))    #两个都好截取子串

字符串的比较

python中用“==”和“!=”比较两个字符串的内容

str1 = 1
str2 = '1'
if str1 == str2:
    print("相等")
else:
    print("不相等")

if str(str1) == str2:
    print("相等")
else:
    print("不相等")

startwith()和endwith()

word = "hello world"
print("hello" == word[0:5])
print(word.startswith("hello"))
print(word.endswith("ld",  6))
print(word.endswith("ld",  6,  10))
print(word.endswith("ld",  6,  len(word)))

字符串的反转

通过切片将字符串反序输出

print(word[::-1])
for i in range((len(word)), 0, -1):
   print(word[i-1])

字符串的查找和替换

字符串的查找用find()方法,返回字符第一次出现时候的索引

word1 = "this is a apple"
print(word1.find("a"))
print(word1.rfind("a"))

python使用replace()实现字符串的替换

sentence = "hello world,hello china"
print(sentence.replace("hello", "hi"))
print(sentence.replace("hello", "hi", 1))

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

EmbodiedTech

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

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

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

打赏作者

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

抵扣说明:

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

余额充值