Python字符串类型

字符串

    字符串,就是由零个或多个字符组成的有限序列。
    Python中,使用单引号或双引号包围起来的单个或多个字符,就可以表示一个字符串。
    字符串中的字符可以是特殊符号、英文字母、中文字符、希腊字母,包括Emoji字符等。

转义字符

    可以在字符串中使用反斜杠 " \ " 来表示转义," \ “后面的字符不再是它原来的意义,例如:\n不是代表反斜杠和字符n,而是表示换行;\t也不是代表反斜杠和字符t,而是表示制表符。所以如果字符串本身又包含了’、”、\这些特殊的字符,必须要通过\进行转义处理。

a = '\'hello, world!\''
print(a) # 'hello, world!'
b = '\\hello, world!\\'
print(b) # \hello, world!\

    Python中的字符串可以 r 或 R 开头,这种字符串被称为原始字符串,意思是字符串中的每个字符都是它本来的含义,没有所谓的转义字符。

# 字符串a中\t指制表符,\n表示换行符
a = '\tears fall dow\n'
print(a)"""	ears fall dow
			
		 """
# 字符串b中没有转义字符,每个字符都是原始含义
b = r'\tears fall dow\n'
print(b) # \tears fall dow\n

字符串的运算

  • 拼接
a = 'My' + 'name'
print(a) # My name
  • 重复
b = a * 3 # a = My name
print(b) # My nameMy nameMy name
  • 比较
         字符串的大小比较比的是每个字符对应的Unicode编码的大小。关于字符对应的编码到底是多少,可以使用ord函数来获得。
         Python中还有一个is运算符(身份运算符),用来比较的是两个变量对应的字符串是否在内存中相同的位置(内存地址)。
a = 'hello world'
b = 'worle hello'
c = 'hello world'
print(a == b) # False
print(a != b) # True
print(a < b) # True
print(ord('博'),ord('客')) # 21338 23458
print(a == c,b == c) # True False
print(a is c,b is c) # True False

  • 成员运算
        Python中可以用in和not in判断一个字符串中是否存在另外一个字符或字符串,运算结果会产生布尔值True或False
a = 'hello world'
b = 'hello'
print(b in a) # True
  • 获取字符串长度
    使用内置函数len来获取字符串长度
a = 'hello world'
print(len(a)) # 11
  • 索引和切片
    索引:返回第n个字符
a = 'hello world'
print(a[1]) # e

       切片:返回索引第 n 到第 m 的字符子串,不包括 m 。

a = 'hello world'
print(a[1:4]) # ell
  • 遍历
a = 'hello world'
for str in a:
    print(str)

字符串的方法

  • 查找
    find和index方法从字符串中查找另一个字符串所在的位置,找到了返回字符串中另一个字符串首字符的索引,不同的是,找不到时,find返回“ -1 ”,index则引发异常。
a = 'hello world'
print(a.find('e')) # 1
print(a.index('e')) # 1
print(a.find('boy')) # -1
print(a.index('boy')) # ValueError: substring not found

这两种方法还有更丰富的使用方法,大家可以在python使用手册里学习

  • 性质判断
    可以通过字符串的startswith、endswith来判断字符串是否以某个字符串开头和结尾;还可以用is开头的方法判断字符串的特征,这些方法都返回布尔值,
a = 'hello, world!'
print(a.startswith('He'))    # False
print(a.startswith('hel'))   # True
print(a.endswith('!'))       # True

s2 = 'abc123456'
# isdigit方法检查字符串是否由数字构成返回布尔值
print(s2.isdigit())    # False
# isalpha方法检查字符串是否以字母构成返回布尔值
print(s2.isalpha())    # False
# isalnum方法检查字符串是否以数字和字母构成返回布尔值
print(s2.isalnum())    # True
  • 格式化字符串
    在Python中,字符串类型可以通过center、ljust、rjust方法做居中、左对齐和右对齐的处理。
s = 'hello, world'

# center方法以宽度20将字符串居中并在两侧填充*
print(s.center(20, '*'))  # ****hello, world****
# rjust方法以宽度20将字符串右对齐并在左侧填充空格
print(s.rjust(20))        #         hello, world
# ljust方法以宽度20将字符串左对齐并在右侧填充~
print(s.ljust(20, '~'))   # hello, world~~~~~~~~

有关格式化字符的更多操作,可以看这里

  • 修剪
    字符串的strip方法可以帮我们获得将原字符串修剪掉左右两端空格之后的字符串。
a = '\nhello, world\t'
print(a.strip())    # hello, world
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值