2020.06.11--预习课--第5节--字符串

一、字符串

1、字符串的声明格式

>>> a = 'a'
>>> a
'a'
>>> a = "a"
>>> a
'a'
>>> a = '''a'''
>>> a
'a'
>>> a = """a"""
>>> a
'a'
>>> 

 

1.1、单引号中包含单引号---报错

>>> s = 'i'm a boy'
  File "<stdin>", line 1
    s = 'i'm a boy'
           ^
SyntaxError: invalid syntax
>>> 

 

1.2、双引号中包含双引号--报错

>>> s = "you "are" a good man!"
  File "<stdin>", line 1
    s = "you "are" a good man!"
                ^
SyntaxError: invalid syntax
>>> 

 

1.3、同种引号要想不报错,可以使用转义符号

1.3.1、单引号中

>>> s = 'I\'m a boy'
>>> s
"I'm a boy"
>>> 

 

1.3.2、双引号中

>>> s = "you \"are\" a good man!"
>>> s
'you "are" a good man!'
>>> 

 

1.4、双引号包含单引号,不会报错

>>> s = "I'm a girl!"
>>> s
"I'm a girl!"
>>> 

 

1.5、单引号包含双引号,不会报错

>>> s = 'you a "bad" woman!'
>>> s
'you a "bad" woman!'
>>> 

 

1.6、三引号可以保留格式,单和双区别不大

1.6.1、单三引号

>>> s = '''
... *******
... 日期 |支出|收入|事项|结余
... 8-2  |2.00|3.00|吃啦|200
... *******
... '''
>>> print(s)

*******
日期 |支出|收入|事项|结余
8-2  |2.00|3.00|吃啦|200
*******

>>> 

 

1.6.2、双三引号

>>> s = """
... *******
... 日期 |支出|收入|事项|结余
... 8-2  |2.00|3.00|吃啦|200
... *******
... """
>>> print(s)

*******
日期 |支出|收入|事项|结余
8-2  |2.00|3.00|吃啦|200
*******

>>> 

 

2、转义符--换行:\n     回车:\r    制表符:\t

2.1、换行:\n;把当前行,切换到下一行。在历史的打字机中,切换到下一行后还是在上一行最后的这个位置

>>> print('a\nb')
a
b
>>> 

 

2.2、回车:\r ;把光标键的位置切换到当前行的最开始位置

>>> print('a\rb')
b
>>> 

 

2.3、windows中换行默认使用\r\n

>>> print('a\r\nb')
a
b
>>> 

 

2.4、制表符:\t

>>> print('a\tb')
a    b
>>> 

 

2.5、如何打印斜杠,两个斜杠;如果只有一个斜杠,遇到某些特殊字母会被转义

>>> print('a\\b')
a\b
>>> print('a\b')
a
>>> 

 

>>> print('a\bcb')
cb
>>> print('a\eecb')
a\eecb
>>> print('a\ffeecb')
a
 feecb
>>> print('a\affeecb')
affeecb
>>> print('a\caffeecb')
a\caffeecb
>>> print('a\dcaffeecb')
a\dcaffeecb
>>> print('abcdef\dcaffeecb')
abcdef\dcaffeecb
>>> print('abcdef\d')
abcdef\d
>>> print('abcdef\\d')
abcdef\d
>>> print('abcdef\\\d')
abcdef\\d
>>> 
其他情况

 

2.6、元字符 r R,大小写皆可,不转义,原来啥样,就是啥样

>>> print(r'a\b')
a\b
>>> print(r'a\\b')
a\\b
>>> print(r'a\n\b')
a\n\b
>>> 

 

2.7、在交互模式和print下的区别,交互模式下,不会转义;在print下会转义

>>> print('a\\b')
a\b
>>> 'a\\b'
'a\\b'
>>> 'a\nb\rd'
'a\nb\rd'
>>> print( 'a\nb\rd')
a
d
>>> 

 

3、模板字符

3.1、模板字符串:%s、%d、%f

3.1.1、%s  所有的模板类型都可用%s

>>> print("hello,%s"% 'Mary')
hello,Mary
>>> print("hello,%s"%100)
hello,100
>>> print("hello,%s"%1.111)
hello,1.111
>>> print("hello,%s"%[1,2,3])
hello,[1, 2, 3]
>>> print("hello,%s"%[1,2,3][1])
hello,2
>>> print("hello,%s"%(1,2,3)[1])
hello,2
>>> print("hello,%s"%{1:a,2:b}[1])
hello,a
>>> 

 

3.1.2、 %d 整数类型可用

>>> a = -1
>>> print("你有%d元"%a)
你有-1元
>>> a = 6.698
>>> print("你有%d元"%a)
你有6元
>>> a = [1,2,3]
>>> print("你有%d元"%a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not list
>>> print("你有%d元"%a[2])
你有3元
>>> a = '2'
>>> print("你有%d元"%a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>> a = {a:1,b:2,c:100}
>>> print("你有%d元"%a[c])
你有100元
>>> print("你有%d元"%a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not dict
>>> 

 

3.1.3、%f 可以取到小数位数(四舍五入,奇进偶不进)

>>> n = 12345.9876
>>> print("你现在有%1f元钱"%n)
你现在有12345.987600元钱
>>> print("你现在有%4f元钱"%n)
你现在有12345.987600元钱
>>> print("你现在有%.4f元钱"%n)
你现在有12345.9876元钱
>>> print("你现在有%.3f元钱"%n)
你现在有12345.988元钱
>>> print("你现在有%.2f元钱"%n)
你现在有12345.99元钱
>>> print("你现在有%.1f元钱"%n)
你现在有12346.0元钱
>>> print("你现在有%.0f元钱"%n)
你现在有12346元钱
>>> print("你现在有%-.1f元钱"%n)
你现在有12346.0元钱
>>> 

 

3.1.4、参数可以传多个

hello,I现在负债100元钱
>>> print("%s,%s现在%s%d元钱"%('hello','I','',100))
hello,I现在有100元钱
>>> 

 

3.2、format

>>> print('{0},my name is {1},i am {2} {3}'.format('hello','Lily','a','girl'))
hello,my name is Lily,i am a girl
>>> print('{0},my name is {1},i am {2} {1}'.format('hello','Lily','a','girl'))
hello,my name is Lily,i am a Lily
>>> print('{问候语},my name is {姓名},i am {量词} {姓名}'.format(问候语='hello',姓名='Lily',量词='a','girl'))
  File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument
>>> print('{问候语},my name is {姓名},i am {量词} {姓名}'.format(问候语='hello',姓名='Lily',量词='a'))
hello,my name is Lily,i am a Lily
>>> print('{问候语},my name is {姓名},i am {量词} {姓名}'.format(问候语='hello',姓名='Lily',量词='a',随便='girl'))
hello,my name is Lily,i am a Lily
>>> 

 

4、字符串的遍例

方法1:每一个直接取出来,不需要关心位置的时候。

方法2:基于字符串的坐标位置做遍历,需要关心字符的位置。

5、字符串是否可以改变?

回答:不可以,每次你看到的字符串内容变化,其实都是生成了新的字符串。id 已经变了

>>> s="abc"
>>> id(s)
4263024
>>> s=s+"def"
>>> id(s)
39266768

 

>>> s
'abcdef'
>>> s[0]
'a'
>>> s[0]="z"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

 

6、切片:正着取、倒着取、跳着取

>>> s = '1234567890'
>>> s[:6]
'123456'
>>> s[4:6]
'56'
>>> s[4:6:-1]
''
>>> s[::-1]
'0987654321'
>>> s[6:4:-1]
'76'
>>> s[::2]
'13579'
>>> s[-1:-4:-1]
'098'
>>> s[-1:-4:1]
''
>>> 

 

7、内置常用方法

7.1、长度:len()

>>> s = '1234567890'
>>> len(s)
10
>>> 

 

7.2、以xxx开头:startswith()

>>> s
'Intel Corporation  Investor Relations'
>>> s.startswith('In')
True
>>> s.startswith('in')
False

 

7.3、以XXX结束:endswith()

>>> s
'Intel Corporation  Investor Relations'
>>> s.endswith('in')
False
>>> s.endswith('ons')
True
>>> 

 

7.4、标题格式(每个单词的首字母大写):title()

>>> s
'intel corporation  investor relations'
>>> s.title()
'Intel Corporation  Investor Relations'
>>> 

 

7.5、全部大写:upper()

>>> s
'Intel Corporation  Investor Relations'
>>> s.upper()
'INTEL CORPORATION  INVESTOR RELATIONS'
>>> 

 

7.6、全部小写:lower()

>>> s
'Intel Corporation  Investor Relations'
>>> s.lower()
'intel corporation  investor relations'
>>> 

 

7.7、句子的句首为大写字母:capitalize()

>>> s
'intel corporation  investor relations'
>>> s.capitalize()
'Intel corporation  investor relations'
>>> 

 

7.8、统计:count()

>>> s
'intel corporation  investor relations'
>>> s.count('o')
5
>>> 

 

7.9、找到第一个xxx的位置:index(),如果没有,会报错

>>> s
'intel corporation  investor relations'
>>> s.index('o')
7
>>> s.index('0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> 

 

7.10、查找第一个xxx的位置:find(),如果没有,会返回-1

>>> s
'intel corporation  investor relations'
>>> s.find('o')
7
>>> s.find('0')
-1
>>> 

 

7.11、去掉某些字符:strip()、lstrip()、rstrip()

7.11.1、strip()

>>> a = '    abcd  \t  abc \t\n    '
>>> a
'    abcd  \t  abc \t\n    '
>>> a.strip()
'abcd  \t  abc'
>>> m = '***sjhgalsj***我'
>>> m.strip('*')
'sjhgalsj***我'
>>> m.strip('')
'***sjhgalsj***'
>>> 

 

7.11.2、lstrip()

>>> a
'    abcd  \t  abc \t\n    '
>>> a.lstrip()
'abcd  \t  abc \t\n    '
>>> m
'***sjhgalsj***我***'
>>> m.lstrip('*')
'sjhgalsj***我***'
>>> 

 

7.11.3、rstrip()

>>> a
'    abcd  \t  abc \t\n    '
>>> a.rstrip()
'    abcd  \t  abc'
>>> m
'***sjhgalsj***我***'
>>> m.rstrip()
'***sjhgalsj***我***'
>>> m.rstrip('*')
'***sjhgalsj***我'
>>> 

 

7.12、对齐:ljust()、rjust()、center()

7.12.1、左对齐ljust(),第二个参数必须要有内容,不能使空字符串,可以是空格字符串,只能是单个的字符串

>>> n
'Hello Wrld'
>>> n.ljust(20, '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
>>> n.ljust(20, ' ')
'Hello Wrld          '
>>> n.ljust(20, '*')
'Hello Wrld**********'
>>> 

 

7.12.2、右对齐rjust(),只能是单个的字符串

>>> n
'Hello Wrld'
>>> n.rjust(20,'')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
>>> n.rjust(20,' ')
'          Hello Wrld'
>>> n.rjust(20,'*')
'**********Hello Wrld'
>>> n.rjust(20,'*-')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
>>> 

 

7.12.3、居中对齐center()

>>> n
'Hello Wrld'
>>> n.center(20,'*')
'*****Hello Wrld*****'
>>> 

 

7.13、全部替换replace(),可以指定替换数量,只能从左开始

>>> v = 'abcadeafghaijkalmanaopakarstauvawaxayaz'
>>> v.replace('a','*')
'*bc*de*fgh*ijk*lm*n*op*k*rst*uv*w*x*y*z'
>>> v.replace('a','*',5)
'*bc*de*fgh*ijk*lmanaopakarstauvawaxayaz'
>>> v.replace('a','*',-5)
'*bc*de*fgh*ijk*lm*n*op*k*rst*uv*w*x*y*z'

 

 

二、练习

题目1: s="abcabcdef" 统计一下c出现了几次

s = "abcabcdef"
count = 0
for i in s:
    if i == 'c':
        count += 1
print(count)
统计c的次数

 

 

题目2: s="abcabcdef" 统计一下c所有出现的位置

s = "abcabcdef"
result = []
for i in range(len(s)):
    if s[i] == 'c':
        result.append(i)
print(result)
C的坐标位置

 

题目3:把所有字符串中的c替换为*

编程思想:
    既然不能改变我就转换成一个可以改变的类型。----》list
    修改之后,我在变为字符串类型
编程思想:

 

s = "abcabcdef"
s = list(s)
for i in range(len(s)):
    if s[i] == 'c':
        s[i] = '*'
# s = ''.join(s)
print(''.join(s))
c替换为*

 

题目4:word_list = ["hello","glory","road"] ,请把每个单词的最后两个字母拼成一个字符串

word_list = ["hello", "glory", "road"]
result = ''
for i in range(len(word_list)):
    result += word_list[i][-2:]
print(result)
方法一:
word_list = ["hello", "glory", "road"]
result = ''
for i in word_list:
    result += i[-2]+i[-1]
print(result)
方法二:
word_list = ["hello", "glory", "road"]
result = ''
for i in word_list:
    result += i[len(i)-2:]
print(result)
方法三:

 

 

三、作业

写3个你职业生涯中最有技术价值的bug

1 描述清楚bug是什么
2 怎么发现的,说说曲折经历
3 用到了什么技术发现的
4 bug严重程度
5 bug出现的原因

 

posted @ 2020-06-11 16:49  梦风灵舞  阅读(203)  评论(0编辑  收藏  举报