字符串(string)
1.字符串的表现形式为:变量名=“ string ”或变量名=‘ string ’或 变量名=""" string """,比如:
str1 = ‘hello, world!‘ str2 = "hello, world!" str3 = "子曰:‘学而时习之,不亦说乎‘" str4 = ‘‘‘ 离离原上草, 一岁一枯荣。 野火烧不尽, 春风吹又生。 ‘‘‘ str5 = """ 江山代有人才出, 各领风骚数百年。 """ print(str1) print(str2) print(str3) print(str4) print(str5)
hello, world!
hello, world!
子曰:‘学而时习之,不亦说乎‘
离离原上草,
一岁一枯荣。
野火烧不尽,
春风吹又生。
江山代有人才出,
各领风骚数百年。
查看字符串中所有的方法
help(dir(str))
2字符串的常用功能
2.1常用功能之索引:str[index]
字符串从左往右的索引下标是从0开始,从右往左索引下标从-1开始,比如:
# 要求:取出字符串中的!和h # 从左往右 str1 = "hello,world!" print(str1[0]) # h print(str1[11]) # ! # 从右往左 print(str1[-1]) # ! print(str1[-12]) # h
2.2 常用功能之长度len()
这个方法可以用来查看字符串的长度,比如:
print(len(str1)) # 12
2.3 字符串常用功能之切片
字符串的切片可以一次性取出多个元素,比如:
str2 = "hello, world!" # 切片取出字符串中的元素,包前不包后,取出str1中的wo,取出的方法有两种 # 方法1:从左往右取 print(str2[7:9]) # wo # 方法2:从右往左取 print(str2[-6:-4]) # wo
字符串切片之步长
str2 = "hello, world!" # 字符串的步长 # 通过步长取出h和o,此处省略了写h的下标 print(str2[:5:4]) # ho print(str2[:-8:4]) # ho
字符串切片之逆序
字符串切片的逆序是通过控制步长的方向,当步长为整数的时候为正序,当步长为负数的时候为逆序
str2 = "hello, world!" print(str2[::-1]) # !dlrow ,olleh print(str2[::-4]) # !ooh
2.4 字符串常用功能之类方法
类方法的调用通过句点法 类对象.类方法(参数)
2.4.1 类方法之Capitalize
# capitalize方法调用的源码
def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """中文解释:字符串S调用capitalize, S.capitalize()调用返回一个首字母大写,其余字母都为小写的字符串
str2 = "hello ,world!" print(str2.capitalize()) # Hello , world!
2.4.2 类方法之Casefold
将字符串中的大写字母改成小写字母
str2 = "HELLO WORLD!" str3 = "HelLo world!" """ S.casefold() -> str Return a version of S suitable for caseless comparisons. """ # 返回一个小写字母的字符串 print(str2.casefold()) # hello world! print(str3.casefold()) # hello world!
2.4.3 常用功能之lower和islower
lower
str2 = "HELLO WORLD!" str3 = "HelLo world!" """ S.lower() -> str Return a copy of the string S converted to lowercase. """# 返回一个转换为小写s字符串的副本 print(str2.lower()) # hello world print(str3.lower()) # hello world
islower
str2 = "HELLO WORLD!" str3 = "HelLo world!" str4 = "hello world!" """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ # 字符转中所有的字母都是小写的返回布尔值True,如果字符串S中至少包含一个非小写字母的,返回布尔值False print(str2.islower()) # False print(str3.islower()) # False print(str4.islower()) # True
2.4.4 字符串常用功能之center
str2 = "hello world!" """ S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ # width 指定字符串的长度,fillchar指定 # 返回S,以长度为宽度的字符串为中心。 填充为使用指定的填充字符完成(默认为空格) print(str2) # hello world! print(str2.center(20)) # hello world! print(str2.center(20,"*")) # ****hello world!****
2.4.5 字符串常用功能之count
""" S.count(sub[, start[, end]]) -> int Return the number of non-overlapping(不覆盖) occurrences(发生) of substring(子字符串) sub in string S[start:end]. Optional arguments start and end are interpreted(解释的) as in slice(默认) notation(符号). """ str2 = "hello world!" print(str2.count("l")) # 3 print(str2.count("l", 3)) # 2 print(str2.count("l", 3, 8)) # 1
2.4.6 字符串常用功能之endswith
str2 = "hello world!" """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ print(str2.endswith("!")) # True print(str2.endswith("d")) # False print(str2.endswith("l", 2, 10)) # True print(str2.endswith("l", 2, 8)) # False
2.4.7 字符串常用功之find
str5 = "hello world!" """ S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ print(str5.find("l")) # 2 print(str5.find("l", 5)) # 9 print(str5.find("l", 5, 12)) # 9
2.4.8 字符串常用功能之index
str6 = "hello world!" """ S.index(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found. """ print(str6.index("l")) # 2 print(str6.index("l", 3)) # 3 print(str6.index("l", 3, 5)) # 3
2.4.9 字符串常用功能之isalnum
str6 = "hello " str7 = "hello"str8 = "888"str9 = "888!" """ S.isalnum() -> bool Return True if all characters in S are alphanumeric(字母数字) and there is at least one character in S, False otherwise. """ print(str6.isalnum()) # False print(str7.isalnum()) # True
print(str8.isalnum()) # Trueprint(str9.isalnum()) # False
2.4.10 字符串常用功能之isalpha
str7 = "hello" str8 = "888" """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ print(str7.isalpha()) # True print(str8.isalpha()) # False
2.4.10 字符串常用功能之format
print("My name is {0}, i am {1} years old".format("zgzeng", 23)) # My name is zgzeng, i am 23 years old """ S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}‘). """
这个方法通常用作格式化字符串
2.4.11 字符串常用功能之isdigit
str7 = "888" str8 = "88 " """ S.isdigit() -> bool Return True if all characters in S are digits(数字) and there is at least one character in S, False otherwise. """ print(str7.isdigit()) # True print(str8.isdigit()) # False
2.4.12 字符串常用功能之isspace
str7 = "HELLO WORLD!" str8 = "hello world!" """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ print(str7.isupper()) # True print(str8.isupper()) # False
2.4.13 字符串常用功能之join
li = ["hello", "world", "!"] """ S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ str9 = "-".join(li) print(str9) # hello-world-!
2.4.14 字符串常用功能之strip+lstrip + rstrip
strip
str10 = " hello world " """ S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ str11 = str10.strip() print(str11.strip()) # hello world print(str11.strip("h")) # ello world
lstrip,rstrip
str10.lstrip() """ S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ print(str10) # hello world print(str10.lstrip()) # hello world print(str10.rstrip()) # hello world print(str11) # hello world print(str11.lstrip("l")) # hello world print(str11.rstrip("l")) # hello world
2.4.15 字符串常用功能之split
str12 = "hello world" """ S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ print(str12.split(" ")) # [‘hello‘, ‘world‘] print(str12.split("l")) # [‘he‘, ‘‘, ‘o wor‘, ‘d‘] print(str12.split("l", 2)) # [‘he‘, ‘‘, ‘o world‘] print(str12.split("l", 3)) # [‘he‘, ‘‘, ‘o wor‘, ‘d‘]
3. 字符串的格式化
什么是字符串的格式化,简而言之就是对字符串设定特定的格式
对 year = 2019, month = 11, day = 20,设定为2019-11-20的格式
字符串的格式化方法1:%s
year = 2019 month = 6 day = 3 print("%s-%s-%s" % (year, month, day)) print("%s-%s-%02s" % (year, month, day)) # %02s的意义就是宽度为2,剩余的用0补齐 2019-6-03
print("%d-%0d-%02d" % (year, month, day)) # d代表整数 2019-06-03
字符串的格式化方法2:format
# format python中特有的 test = "name:%s, age:%d, %s" % ("zgzeng", 23, "it") print(test) # name:zgzeng, age:23, it test1 = "name:{}, age:{:04}, {}".format("zgzeng", 23, "it") # 04的意思也是总宽度为4,不足为用0补足
# name:zgzeng, age:0023, it
print(test1)
字符串的格式化的浮点数
f = 3.141 print("%f" % f) # 3.141000
# 指定位数 print("%06f" % f) # 表示小数点后面有6位,不足位用0补足 # 3.141000 print("%06.02f" % f) # 表示总长度为6位,小数后有2位,不足位用0补足 # 003.14
解包
# 解包 test2 = "name:{0}, age:{1}, {0}".format(*["zgzeng", 23]) # 通过解包,在括号里面填入index test3 = "name:{name}, age:{age}, {name}".format(**{"name": "x", "age": 18}) # 因为传入的是一个字典,所以我们不能用index,只能通过键传入值 print(test2) # name:zgzeng, age:23, zgzeng print(test3) # name:zgzeng, age:18, zgzeng
指定位数
# 指定位数 test2 = "name:{0}, age:{1}, {0}".format(*["zgzeng", 23]) # 通过解包,在括号里面填入index test3 = "name:{name}, age:{age:04}, {name}".format(**{"name": "x", "age": 18}) # 因为传入的是一个字典,所以我们不能用index,只能通过键传入值 print(test2) # name:zgzeng, age:23, zgzeng print(test3) # name:x, age:0018, x
test = "numbers: {:b},{:o}, {:x}, {:X}, {:%}" .format(10, 1, 1, 1, 1)print(test) # numbers: 1010,1, 1, 1, 100.000000%
原文地址:https://www.cnblogs.com/zgzeng/p/11863020.html