字符的定义和操作
字符不具有修改的性质。
字符的定义:
# define a = "Hello,world!" b = 'Python is cool!' c = str(range(4)) print(a) # Hello,world! print(b) # Python is cool! print(c) # range(0, 4)
字符的简单操作:
# 访问值 print(a [0]) # H print(a [0:4]) # Hell print(a [:4]) # Hell print(a [4:-1]) # o,world print(a [4:]) #可以取到最后一位 # o,world! # 不可修改. # 通过重新赋值的方式来“改变”一个已有的字符串。新的值,可以和新的差不多,也可能和原有的字符串完全不同。 # change a = a [0:6] + "python" # Hello,python print(a) a = 'this is a new world for me' print(a) # this is a new world for me
字符的.XXXX操作:
# operation print(a.count("is")) # 2 print(a.capitalize()) # 首字母大写 # This is a new world for me print(b.casefold()) # python is cool! print(a.center(50,"*")) # ************this is a new world for me************ print(a.encode("utf-8")) # 转码 # b'this is a new world for me' print(a.endswith("hbb")) # 判断是否以“ ”结束 # False print("hbb\tbing".expandtabs(20)) #将\t换成多少的空格 # hbb bing print(a.find("a")) # 8 print(a.find("g")) # -1 # format: introdution = """ -------info of {}--------- my name is {},\nand age is {}""" print(introdution.format("hbb","hbb",22)) introdution = """ -------info of {0}--------- my name is {0},\nand age is {1}""" print(introdution.format("hbb",22)) introdution = """ -------info of {name}--------- my name is {name},\nand age is {age}""" print(introdution.format(name = "hbb",age=22)) # a.format_map() print(a.index("a")) # 8 d = "b8b" e = "8bB" print(d.isalnum()) # 是否为字符 # True print(d.isalpha()) # 是all字母 print(e.isdecimal()) # 是否是小数 print(e.isdigit()) # 是否都为数字 print(d.islower()) # 小写? print(e.isupper()) # big write print(d.isnumeric()) print(d.isspace()) print(d.isprintable()) print("|".join("h""b""b")) # h|b|b intab = "abcdef" outtab = "123456" new = a.maketrans(intab,outtab) # 不懂什么鬼 print(new) print(a.partition("e")) # 以“”划分 (第一个) # ('this is a n', 'e', 'w world for me') print(a.swapcase()) # 大小写互换 # THIS IS A NEW WORLD FOR ME print(a.startswith("t")) print(a.zfill(30)) # 0000this is a new world for me print(a.center(30,"*")) # **this is a new world for me** print(a.rjust(30,"*")) # ****this is a new world for me print(a.ljust(30,"*")) # this is a new world for me****
东西很多,也很常用,不妨当工具来看。