python(day012——字符串1)

本文深入讲解了Python中字符串的各种操作技巧,包括字符串类型判断、编码转换、格式化、遍历和切片等核心内容,适合Python初学者及需要巩固字符串处理技能的开发者阅读。

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

>>> s="abc"
>>> type(s)
<class 'str'>
>>> s.encode("gbk")
b'abc'
>>>
>>> s=s.encode("gbk")
>>> type(s)
<class 'bytes'>
>>> s="中国"
>>> type(s)
<class 'str'>

1.单引号/双引号/三引号

>>> a="加油"
>>> a='加油'
>>> a="""加
... 油
... 少
... 年"""
>>> a
'加\n油\n少\n年'


#双引号里面打印引号:加\
>>> a="hello\"world"
>>> a
'hello"world'

2.\t和\n,\r,\

>>> a="a\tb"
>>> print(a)
a       b
>>> a="a\nb"  #换行符
>>> print(a)
a
b
>>> a="a\rb\rhello"  #\r回车符,用得少
>>> print(a)  #显示最后的内容
hello

#查看操作系统的回车符
>>> import os
>>> os.linesep
'\r\n'

#输出\
>>> a="a\\b"
>>> print(a)
a\b

3.模板字符串

>>> s="my name is %s and gender is %s" %("wang","F")
>>> s
'my name is wang and gender is F'


#当使用模板字符串时想打印%,需要写%%
>>> s="90%% %s" %"boy"
>>> s
'90% boy'
>>> s="%d%% boy" %90
>>> s
'90% boy'
  • %s:百无禁忌
  • %d:必须是整数
  • %f:必须是浮点数。%。1f:表示保留一位小数
>>> s="test:%.1f" %1.365
>>> s
'test:1.4'

其余两种方式:

>>> from string import Template
>>> a=Template('would it be the ${key1} when we meet in ${key2}')
>>> a.substitute(key1='same',key2='heaven')
'would it be the same when we meet in heaven'



>>> "{0},your {1}".format("hello", "world")
'hello,your world'

4.遍历字符串

>>> s="gloryroad"
>>> for i in s:  #穷举
...    print(i)
...

#基于坐标 
>>> for i in range(len("hello")):


#取值,不要越界
>>> s
'helloworld'
>>> s[-1]
'd'
>>> s[-2]
'l'
>>> s[0]
'h'
>>> s[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

练习:统计“helloworld”中几个“o”

>>> result=0
>>> for i in "helloword":
...     if i=="o":
...         result+=1
...
>>> print (result)
2

#统计“helloworld”中出现“o”的位置
>>> s="helloworld"
>>> for i in range(len(s)):
...     if s[i]=="o":
...         print("在第%d位置出现o" %(i+1))
...
在第5位置出现o
在第7位置出现o

*切片(有“:”):

>>> s
'helloworld'
>>> s[:2]  #取2位置之前所有的字符串,不包含2位置
'he'
>>> s[3:5]  #取从3到5之前,不包含5
'lo'

>>> s[1::2]  #步长
'elwrd'
>>> s[::3]
'hlod'

#逆序
>>> s[-1:-3:-1]
'dl'
>>> s[-3:-1]
'rl'
>>> s[-1:-3:-2]
'd'
>>> s[-1::-1]
'dlrowolleh'

5.修改字符串

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值