python入门(七):字符串

1.字符串类型:

>>> s="早上好"               #str类型的字符串

>>> type(s)

<class 'str'>

>>> s=s.encode("utf-8")          #bytes类型的字符串

>>> type(s)                     #bytes类型主要用于网络传输和写入文件

<class 'bytes'>

>>> isinstance(s,bytes)            #判断字符串是否是bytes类型

True

>>> isinstance(s,str)              #判断字符串是否是str类型

False

>>> print(s)                     #打印bytes类型时,是有很多编码的

b'\xe6\x97\xa9\xe4\xb8\x8a\xe5\xa5\xbd'

>>> s=s.decode("utf-8")        

>>> print(s)                     #打印str类型,可显示易于理解的样式

早上好

2.字符串地址

>>> s="a"                       #在python3中,如果字符串为英文且内容一样,那么

>>> id(s)                        #存储的地址也是一样,两个是同一个对象

2681370639976

>>> s1="a"

>>> id(s1)

2681370639976

>>> s is s1

True

>>> s="早上好"               #在python3中,如果字符串是中文的,且内容一样,

>>> id(s)                       #但是两者的id是不一样的,两者不是一个对象

2681370951376

>>> s1="早上好"

>>> id(s1)

2681370614152

>>> s is s1

False

>>> id(s1)                     #字符串是不可改变的,更改字符串后,会生成一个新的

2681370639976                 #字符串

>>> s=s+"*"

>>> id(s)

2681371662912

3.字符串定义

>>> s="早上好"              #双引号可定义字符串

>>> s

'早上好'

>>> s='早上好'               #单引号可定义字符串

>>> s

'早上好'

>>> s="""早上好"""           #3个双引号可定义字符串

>>> s

'早上好'

>>> s='''早上好'''              #3个单引号可定义字符串

>>> s

'早上好'

>>> s="She is a girl.\nHe is a boy.\nHe is a man"  #双引号默认单行输出文本

>>> print(s)                     #添加\n,可实现多行输出

She is a girl.

 He is a boy.

 He is a man

>>> s="a\tb\tc"                #\t是制表符

>>> print(s)

a       b       c             #一个\t默认是8个空格

几种定义字符串的区别:

>>> "He's a boy"               #双引号字符串中可包含单引号

"He's a boy"

>>> "'hi' is a word"

"'hi' is a word"

>>> "\"hi\" is a word"           #双引号中可包含双引号,需要加转义符\

'"hi" is a word'

>>> 'He's a boy'               #单引号字符串中不可包含单引号

  File "<stdin>", line 1

    'He's a boy'

        ^

SyntaxError: invalid syntax

>>> '"hi" is a word'             #单引号中可包含双引号

'"hi" is a word'

>>> s="""He                   #三引号(双引和单引)可实现多行输出

... You

... She

... """

>>> print(s)

He

You

She

>>> s="\\"                    #输入\的代码

>>> print(s)                   #print与没有print的输出结果不同,原因在于

\                             #没有print的输出默认调用了刺痛的repr函数

>>> s

'\\'

4.字符串长度

>>> len(s)

11

>>> s

'He\nYou\nShe\n'

5.字符串遍历                #广泛用于统计和查找

>>> s="abcdef"               #第一种字符串遍历的方式

>>> for i in s:

...     print(i)

...

a

b

c

d

e

f

>>> s

'a boy,happy,road'

>>> for i in range(len(s)):        #第二种字符串遍历方法:基于位置坐标遍历

...     print(s[i])

...

a

b

o

y

,

h

a

p

p

y

,

r

o

a

d

6.in  not in                   #判断是否在字符串中

>>> "s" not in "abd"

True

>>> "a" in "abd"

True

>>> 1 in [1,2,3,4]               #列表中也可用in  not in

True

>>> 1 in (1,2,3,4)               #元祖中也可用in  not in

True

>>> {1:2} in {1:2,3:4}             #字典中不可用in  not in

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: unhashable type: 'dict'

7.字符串拼接

>>> s="abcdefg"               

>>> s[0]+s[-1]                 #切片拼字符串

'ag

>>> s[0:2]+s[-2::]              #前两个和后两个字母拼接

'abfg'                         #切片终点坐标是开区间,不包含

>>> s[::2]                     #取所有偶数坐标的字母

'aceg'

>>> s[1::2]                    #取所有奇数坐标的字母

'bdf'

>>> s[::-1]                    #逆序输出所有字母

'gfedcba'

8.模板字符串

>>> "I am %s years old"%18       #%s可跟任何类型,这里是int

'I am 18 years old'

>>> "My name is %s"%"早上好"  #%s可跟任何类型,这里是str

'My name is早上好'

>>> "I am %d years old"%18     #%d只可跟int类型

'I am 18 years old'

>>> "My name is %s,I am %d years old"%("早上好",18)  #同时又有两个时,要使用元祖

'My name is 早上好,I am 18 years old'

小练习:

1.统计以下有几个a

>>> s="abcdef"

>>> result=0

>>> for i in s:

...     if i=="a":

...         result+=1

...

>>> print(result)

1

2.去掉字符串中的空格和\t

>>> s="a b c \tsdf"                

>>> result=""                      #方法1

>>> for i in s:

...     if i!=" " and i!="\t":

...         result+=i

...

>>> print(result)

abcsdf

>>> s.split()                        #split()将所有的空白字符全部去掉

['a', 'b', 'c', 'sdf']

>>> "".join(s.split())                  #将列表转换为字符串

'abcsdf'

3.判断一句话中,没有a的单词有几个

>>> s="a boy,happy,road"

>>> s=s.split(",")

>>> s

['a boy', 'happy', 'road']

>>> num=0

>>> for i in s:

...     if "a" not in i:

...         num+=1

...

>>> print(num)

0

4.s="I am a boy!",请将该字符串中偶数位置的字母填充*

s="I am a boy!"

s=s.split()

for i in range(0,len(s),2):             #该程序实现有问题,实现的是偶数位置的单词加*

    s[i]=s[i]+"*"                    #需求要求偶数位置的字母加*

print(" ".join(s))                     # s[i]=s[i]+"*"语句本身有问题,字符串不可赋值

运行结果:

E:\>python a.py

I* am a* boy!

正确的代码是:

s="I am a boy!"

result=""

for i in range(len(s)):

    if i%2==0:

        if (s[i]>="a" and s[i]<="z") or (s[i]>="A" and s[i]<="Z"):

            result+=s[i]+"*"

print(result)

运行结果:

E:\>python a.py

I*a*o*

猜你喜欢

转载自www.cnblogs.com/suitcases/p/10362886.html