好好吃饭才是人间的真理

初识字符串

关于python的字符串

什么是字符串?字符串就是有限个字符的序列,比如 'This is a string'

关于字符串的表达方式,有三种,包括"", '', ''' ''',
以三个双引号或单引号开头的字符串可以折行
比如:

s3 = '''
可以随便跨行,通过使用\'\'\'
'''

''是转义符,用来表达原本的意思,比如
print(''')
也可以通过+八进制或者十六进制数以及Unicode编码来表示字符或字符串,比如:

s1 = '\141\142\143\x61\x62\x63'  # 前者是八进制后者是十六进制
s2 = '\u597d\u597d\u5403\u996d'  # 使用Unicode编码

字符串加上r会输出所有内容,不再转义

s1 = r'\141\142\143\x61\x62\x63' #\141\142\143\x61\x62\x63

字符串的运算符:

  • 实现字符串的拼接,比如s1 + s2
  • 实现字符串的多次重复,比如 'hello'*5 #hellohellohellohellohello
    in 判断字符串是否存在于字符串
    not in 与前面相反

字符串索引

s = 'hello'
s[1] #e 取得字符串在第一个的位置字符
s[-1] #0 取得字符串在倒数第一个的位置的字符

字符串的切片操作:

s = 'hello'
s[:] #'hello'
s[1:] #'ello'
s[1:4] #'ell',从1开始,不包括4
s[1::2] #'el',从1开始,每两个
s[::-1] #'olleh',实现逆序

字符串的方法:

s = 'hello world'
s.capitalise() #'Hello world'字符串首字母大写
s.title() #'Hello World',单词首字母大写
s.upper() #'HELLO WORLD',全部大写
s.upper().lower() #'hello world',全部小写
s.find('he') #0 ,,返回字串的位置,若没找到返回-1
s.index('he')#0, 同上只是没找到会报错
s.startswith('he') #True
s.endswith('ld') #True
s.center(50,'#') #'###################hello world####################',以指定宽度居中,填充字符
s.rjust(50,'@') #向右
'123456'.isdigit() #True, 检测是否由数字组成
'aBcd'.isalpha() #True, 检测是否由字母组成
'abcd123'.isalnum() #False, 检测是否由数字和字母组成
' abc  '.strip() #'abc', 去掉两边的空格
' abc  '.rstrip() #' abc', 去掉右边的空格
' abc  '.lstrip() #'abc  ', 去掉左边的空格

字符串的格式化输出

print('%d %s %s'%(1,s1,s2))
print('{0},{2},{1}'.format(1,2,3)) #1,3,2 
a,b = 1,2
print(f'{a} {b} {a+b}') #语法糖,即用更简练的表达写出一样的作用
posted @ 2021-01-29 13:49  好好吃饭3  阅读(11)  评论(0)    收藏  举报