字符串在 Python3 内部字符串是 unicode 编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成 unicode,再从 unicode 编码(encode)成另一种编码。

使用单双引号都可以,这就是一个序列,可以直接使用索引来引用,下标从 0 开始编号。

字符串是不可变对象,修改变量名指向对象时,原来指向的字符串对象会被丢弃(如果没有其它指向时)。

修饰

# 字符串前面加上 r 字符表示原生字符串
# 里面的内容不需要使用转义字符,无论是单引号还是双引号内都代表他本身。
os.chdir(r'C:\Users\Chris\Resources')
str2 = r'/a/a/a/ggg\@#$'

拼接字符串

str = " " + str2 + str3 + str4

常用方法

# 字母处理
str.upper()      # 全部大写
str.lower()      # 全部小写
str.swapcase()   # 大小写互换
str.capitalize() # 首字母大写,其余小写
str.title()      # 首字母大写
 
# 格式化相关
str.ljust(width)  # 转换成固定长度的字符串,左边对齐,右边补空格。
str.rjust(width)  # 转换成固定长度的字符串,右边对齐,左边补空格。
str.center(width) # 转换成固定长度的字符串,居中,左右补空格。
str.zfill(20)     # 转换成固定长度的字符串,右对齐,左边用0补。
 
# 搜索指定字符串
str.find('t')           # 返回下标位置,没找到返回-1。
str.find('t',start)     # 返回下标位置,没找到返回-1,指定开始位置。
str.find('t',start,end) # 返回下标位置,没找到返回-1,指定开始结束位置。
str.rfind('t')          # 从右边开始查找。
str.count('t')          # 返回匹配个数。
 
# 剥去字符:当字符串不符合我们的要求的时候,例如 json 不标准。
str.strip()    # 剥去两边空格,参数:去掉指定的字符。
str.lstrip()   # 剥去左空格,参数:去掉指定的字符。
str.rstrip()   # 剥去右空格,参数:去掉指定的字符。
 
# 分离字符
str.split()    # 默认使用空格拆分字符串
str.split('-') # 指定分隔符进行拆分字符串
 
# 基本判断
str.startswith('start')        # 是否以start开头
str.endswith('end')            # 是否以end结尾
str.isalnum()                  # 是否全数字
str.isalpha()                  # 是否全字母
str.isdigit()                  # 是否全数字
str.islower()                  # 是否全小写
str.isupper()                  # 是否全大写
str.startwith(('str1','str2')) # if or not start with other string
str.endwith(('str1','str2'))   # if or not end with other string
 
# 替换
str.replace('old','new')       # 将old替换为new
str.replace('old','new', 4)    # 将前4个old替换成new
 
# 转换字符编码
str.decode('gb2312')    [[表示将gb2312编码的字符串str1转换成unicode编码。]]
str.encode('gb2312')    [[表示将unicode编码的字符串str2转换成gb2312编码。]]
 
# 组合列表中的字符串
list_1 = ['I', 'Like', 'Python', 'automation']
print(''.join(test))
 
# reverse string
str1[::-1]
 
# 插入字符串
name = "Chris"
time = "下午"
s = f"{name}昨天{time}怎么"

字符串插值

def __str__(self):
 return 'Student Object (name = %s)' % self.name

多行字符

# 多行字符串
# 传统的使用反斜杠
 
str_1 = 'select * from ' \
 'tb_1'
 
# 传统的使用三引号
str_2 = '''select * from
 tb_1'''
 
# 传统的方式会出现空格字符,而且没有缩进不好看,最好是使用括号将内容括起来
str_3 = (
 'select '
 '* '
 'from tb_1 '
)

format 方法

>>> name='zhang'
>>> age=12
>>> print("Hi, I am {} and I am {} years old".format(name, age))
Hi, I am John and I am 12 years old
 
print("... {name}...{age}...".format(name='张三', age=12))

类型转换

print tuple(eval("(1,2,3)"))                   # to tuple
print list(eval("(1,2,3)"))                    # to list
print type(eval("{'name':'Chris', 'age':88}")) # to map
 
# str 转换成bytes
bytes(str1, encoding = "utf8")
str.encode(str1)