5

基本数据类型之字符串 - marsha的世界

 2 years ago
source link: https://www.cnblogs.com/marsha/p/16010631.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

基本数据类型之字符串

一、定义:由一对单引号或双引号包含的一串字符。字符串是不可变类型,字符串之间可以进行加法、乘法的运算,运算的本质就是字符串拼接。

name="marsha"  
age="49"
print(name+age)
print(name*3)

marsha49
namenamename

二、数据类型转换:str() 可以将任意数据类型转换成字符串类型。

#list>str
a=[1,2,3]              #list
a=sir([1,2,3])         #str

#dict>str
a=str({"name":"marsha","age"=49})     #str

#int>str
x=str(57)      #str

#float>str
y=str(3.1415)

#tuple>str
m=str((1,2,3))

#set>str
L=str({1,2,3})

三、内置方法

A、取值:字符串可以按索引取值,可以取全值,可以部分取值;注意:取值不算空格;且,只能取,不能改 ;正向取从0开始数,反向取从-1开始数。

     语法格式: [ ]

msg="hello world"
print(msg)            #取全值
print(msg[5])         #正向取
print(msg[-3])       #反向取

hello world
w
r

B、切片Slice:是一个取操作,不改变原值,属于浅拷贝,即:从一个大字符串中拷贝出一个字符串,正切从0开始数位,空格要算位,切片顾头不顾尾。  完整切片语法格式:object[start_index:end_index:step]。

step:正负数均可,其绝对值大小决定了切取数据时的‘‘步长”,而正负号决定了“切取方向”,正表示“从左往右”取值,负表示“从右往左”取值。当step省略时,默认为1,即从左往右以步长1取值。

start_index:表示起始索引(包含该索引对应值);该参数省略时,表示从对象“端点”开始取值,至于是从“起点”还是从“终点”开始,则由step参数的正负决定,step为正从“起点”开始,为负从“终点”开始。

end_index:表示终止索引(不包含该索引对应值);该参数省略时,表示一直取到数据“端点”,至于是到“起点”还是到“终点”,同样由step参数的正负决定,step为正时直到“终点”,为负时直到“起点”。

  • 开头:当步长>0时,不写默认0。当步长<0时,不写默认-1

  • 结束:当步长>0时,不写默认列表长度加一。当步长<0时,不写默认负的列表长度减一

  • 步长:默认1,>0 是从左往右走,<0是从右往左走

(一)start_index、end_index、step三者可同为正、同为负,或正负混合。但必须遵循一个原则,即:当start_index表示的实际位置在end_index的左边时,从左往右取值,此时step必须是正数(同样表示从左往右);当start_index表示的实际位置在end_index的右边时,表示从右往左取值,此时step必须是负数(同样表示从右往左),即两者的取值顺序必须相同。

(二)当start_index或end_index省略时,取值的起始索引和终止索引由step的正负来决定,这种情况不会有取值方向矛盾,但正和负取到的结果顺序是相反的,因为一个向左一个向右。

(三)step的正负是必须要考虑的,尤其是当step省略时。比如msg[-1:],很容易就误认为是从“终点”开始一直取到“起点”,原因在于step省略时step=1表示从左往右取值,而起始索引start_index=-1本身就是对象的最右边元素了,再往右已经没数据了,因此结果只含有d一个元素。

(四)切片的返回结果类型和切片对象类型一致,返回的是切片对象的子序列。如:对一个列表切片返回一个列表;字符串切片返回字符串。

切片可以全切,正切,反切,还可以加步长切片。全切用[:],[: :]操作,反向全切用[::-1]操作。

msg="hell0 world"
print(msg[:])     #正向全切
print(msg[::-1])   #反向全切
print(msg[0:8])    #正向切,从第一位切到第7位,即0,1,2,3,4,5,6,7
print(msg[0:8:2])   #正向切,步长为2,从第一位开始,两位两位的数,即0,2,4,6,注意,8不能数了,顾头不顾尾
print(msg[5:0:-1])   #反向切,步长位1,起点为5,终点为0,即5,4,3,2,1,0

#输出结果
hello world
dlrow olleh
hello wo
hlow
 olleh

C、长度len:获取字符串的长度,即字符串的个数,起始位置为1。但凡存在于引号内的都算作字符,含空格

msg="hello world!"
print(len(msg))
>>>12

D、成员运算in  和not in:返回布尔值True 或False

msg="hello world"
print(‘hello’ in msg)
print(“hello” not in msg)
>>>
True
False

E、移除字符串首尾的空白字符:strip( ) #空白字符如:空格,\ n   ,\ t;

     移除首尾指定字符: strip (指定字符),如strip(*&$@)

      移除左边的字符:lstrip( )

     移除右边的字符:rstrip( )

msg=“   hello world \n    ”
res="**&hello world%"
print(msg.strip())
print(res.strip(*$%))<br>print(res.lstrip(*&))
>>>
hello world
hello world<br>hello world%

 F、切分:把一个字符串按照某种分隔符号进行切割,得到一个新的列表.

split():从左到右切分,默认以空格作为切分符号;

split('指定符号'):从左到右,按照指定的字符切割字符串;切分可以指定次数,如split(' : ' , 1)

rsplit():从右到左的顺序对字符串进行切分;

rsplit( '指定符号’ ):从右到左切分,按照指定的字符切割字符串。

info="my name is marsha"
msg="marsha:49:max"
print(info.split())
print(msg.split(':',1))
>>>
['my'', 'name', 'is','marsha']
['marsha','49:max']

G、用 for in 循环取出字符中的每一个字符,含符号和空格

info='marsha:49'
for x  in  info
print(x)
>>>
m
a
r
s
h
a
:
4
9

H、字符串改写:lower( )全改小写;upper( )全改大写

msg='MaRsHa'
print(msg.lower())
print(msg.upper())
>>>
marsha
MARSHA

I、判断字符串是否以括号内指定的字符开头:startswith(' '),结果返回布尔值;

    判断字符串是否以括号内指定的字符结尾:endswith (' ')   结果返回布尔值。

msg='my name is marsha'
print(msg.startswith('m'))
print(msg.engswith('i'))
>>>
True
False

J、格式化输出:format

    a:按照位置一一对应传值:%s可以接收任意值,   %d可以接收传的数字

info='my name in %s  my age is  %d'  %('marsha','49')
print(info)
>>>
'my name is marsha my age is 49'

  b:按照位置,用空的{}一一对应传值:{}.format(按中括号个数传值

info='my name is {} my age is {}'.format('marsha',49)
print(info)
>>>
'my name is marsha my age is 49'

   c:不依赖位置传值:{变量名}  .format(变量赋值)

info='my name is {name}{name} my age is {age}'.format(age=49,name='marsha')
print(info)
>>>
'my name is marsha marsha my age is 49'

d:把format传入的多个值当作一个列表,然后按照 {索引}取值

info='my name is {1} my age is {0}'.format('marsha',49)
print(info)
>>>
'my name is 49 my age is marsha'

K、' 指定分隔符  ’ . join(  ):是从可迭代对象中取出多个字符串,然后按照指定的分隔符进行拼接,拼接的结果为字符串。它的使用与split( )相反

res='hello'
print('%'.join(res)
>>>
'h%e%l%l%o'

L、变量名.replace( ) :修改字符串中旧的字符,可以指定修改个数.

msg='my name is marsha,my age is 49'
print(msg.replace('49','20'))
print(msg.replace('my','your',1))
>>>
'my name is marsha, my age is 20'
'your name is marsha,my age is 49'

M、判断字符串是否为纯数字组成用 isdigit()返回布尔值

msg='ab3456'
print(msg.isdigit( ))
>>>
False

N、字符串需要了解的其他操作(略)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK