python对象与类型之序列(list、tuple、str、range)

开始语

python中一切皆为对象。
要想把python掌握好,就得一步一个脚印,掌握各个对象以及各个对象的相关方法及属性。

python的最基本对象包括:
None : Nonetype
数字:int、float、complex、bool
序列:str、tuple、list、range
映射:dict
集合:set、frozenset
我们常用的语法、规则也是对象,常用的对象还有函数。

然后,数据分析中常用到的对象有数组(array)、数据框(DataFrame)以及序列(Series)。

我们还要知道,类的定义实际上就是对对象的相关定义,实例也是对象,只是它是具体化之后的对象。

本文从序列开始。序列都是可迭代的对象。

1、列表list

(1)定义

内置函数 list(s)可将任意 可迭代类型s转换为列表。列表是可变序列。
若s已经是列表,则该函数构建的新列表是s的一个浅复制

(2)方法及属性
方法描述
s.append(x)将一个新元素x添加到s末尾.(增)
s.clear()Remove all items from list.(清除)
s.count(x)Return number of occurrences of x.(计数)
s.copy()Return a shallow copy of the list.(浅复制)
s.extend(t)Extend list by appending elements from the iterable.(增)
s.index(x,[,start=0[,stop,=9223372036854775807]])Return first index of value.(索引)
s.insert(index,x)Insert object x before index.(插)
s.pop(index=-1)Remove and return item at index (default last).(删)
s.remove(x)Remove first occurrence of value x.(删)
s.reverse()Reverse IN PLACE.(颠倒)
s.sort(key=None[, reverse=False])Stable sort IN PLACE.key是一个键函数。(排序)

2、字符串str

(1)定义

内置函数str(s)可将对象转换成字符串。字符串是不可变序列。

(2)方法及属性
s.capitalize()Return a capitalized version of the string.More specifically, make the first character have upper case and the rest lowercase.(首字母大写)
s. casefold()Return a version of the string suitable for caseless comparisons.(全小写)
s.center(width, fillchar=’ ')Return a centered string of length width.Padding(填补) is done using the specified fill character (default is a space,由参数fillchar控制). (中心)
s.count(sub[, start[, end]])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.(计数)
s.encode(encoding=‘utf-8’, errors=‘strict’)Encode the string using the codec(编码解码器) registered for encoding.参数errors用来处理编码错误, The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’.(编码)
s.endswith(suffix[, start[, end]])Return True(返回布尔值) if S ends with the specified suffix, False otherwise.suffix can also be a tuple of strings to try.(结尾)
s.expandtabs(self, /, tabsize=8)Return a copy where all tab characters are expanded using spaces. If tabsize(制表符大小) is not given, a tab size of 8 characters is assumed.(使用空格代替制表符)
s.find(sub[, start[, end]])Return the lowest index(最小索引) in S where substring sub is found,such that sub is contained within S[start:end]. (查找)
s.format(*args, **kwargs)Return a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces (’{’ and ‘}’).(格式化)
S.index(sub[, start[, end]])Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].Raises ValueError (返回错误)when the substring is not found.
s. isalnum()Return True if the string is an alpha-numeric string, False otherwise.(是否是阿拉伯字符)
s. isalpha()Return True if the string is an alphabetic string, False otherwise.(是否是字母字符)
s.isascii()Return True if all characters in the string are ASCII, False otherwise.
s.isdecimal(self, /)Return True if the string is a decimal string, False otherwise.
s.isdigit(self, /)Return True if the string is a digit string, False otherwise.
s.isidentifier(self, /)Return True if the string is a valid Python identifier, False otherwise.(是否是标识符)
s. islower(self, /)Return True if the string is a lowercase string, False otherwise.
s.isnumeric(self, /)Return True if the string is a numeric string, False otherwise.
s. isprintable(self, /)Return True if the string is printable, False otherwise.
isspace(self, /)Return True if the string is a whitespace string, False otherwise.
istitle(self, /)Return True if the string is a title-cased string, False otherwise.(每个单词首字母大写)
s.isupper(self, /)Return True if the string is an uppercase string, False otherwise.
s. join(self, iterable, /)Concatenate any number(任意数量) of strings.The string whose method is called (join前的字符)is inserted in between each given string.
s.ljust(width, fillchar=’ ')Return a left-justified(左对齐) string of length width. Padding is done using the specified fill character (default is a space).
s.lower()Return a copy(复制) of the string converted to lowercase.
s.lstrip( chars=None)Return a copy of the string with leading whitespace removed. If chars is given and not None, remove characters in chars instead.(删除左边)
s.partition(sep)Partition the string into three parts using the given separator.返回列表.(分割)
s.replace(self, old, new, count=-1, /)Return a copy(复制) with all occurrences of substring old replaced by new.参数count 意为Maximum number of occurrences to replace.默认-1表示全替换。 If the optional argument count is given, only the first count occurrences are replaced.(替换)
s.rfind(sub[, start[, end]])Return the highest index(指数最高) in S where substring sub is found,没找到返回-1.
s.rindex(sub[, start[, end]])Return the highest index(指数最高) in S where substring sub is found, Raises ValueError when the substring is not found.
s.rjust(self, width, fillchar=’ ', /)Return a right-justified(右调整) string of length width.
s.rpartition(self, sep, /)Partition the string into three parts using the given separator. This will search for the separator in the string, starting at the end(从末尾开始).
s.rsplit(sep=None, maxsplit=-1)Return a list of the words in the string, using sep as the delimiter string.参数sep是The delimiter according which to split the string.Splits are done starting at the end(结尾) of the string and working to the front.(从后往前)
s.rstrip(self, chars=None)Return a copy of the string with trailing whitespace removed.(删除右边)
s.split(self, /, sep=None, maxsplit=-1)Return a list of the words in the string, using sep as the delimiter string. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.
s.splitlines(self, /, keepends=False)Return a list of the lines in the string, breaking at line boundaries.Line breaks are not included in the resulting list unless keepends is given and true
s.startswith(prefix[, start[, end]])Return True if S starts with the specified prefix(前缀), False otherwise.
s.strip(self, chars=None, /)Return a copy(复制) of the string with leading and trailing whitespace remove. (两边)
s.swapcase(self, /)Convert uppercase characters to lowercase and lowercase characters to uppercase.(大小写互换)
s.title()Return a version of the string where each word is titlecased.(标题化)
s.translate(self, table, /)Replace each character in the string using the given translation table.参数table Translation table(翻译表), which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
s. upper(self, /)Return a copy of the string converted to uppercase. (大写)
s.zfill(self, width, /)Pad(填补) a numeric string with zeros on the left(左边补0), to fill a field of the given width. The string is never truncated.(不会截取)
s.maketrans(x, y=None, z=None, /)Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals.If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

3、元组tuple

(1)定义

内置函数tuple(s)可将对象转换成元组。
元组是不可变序列。

(2)方法及属性
s.count(value)Return number of occurrences of value.(计数)
s.index(value, start=0, stop=9223372036854775807, /)(查)

4、范围range

(1)定义

range(stop),从0开始,步长为1,不包括stop。
range(start, stop[, step]),从start开始,步长为step,不包括stop。

(2)方法及属性
range.count(value)return number of occurrences of value
range.index(value, [start, [stop]])return index of value.Raise ValueError if the value is not present.
range.start返回range的开始处
range.stop返回range的结束处
range.step返回range的步长

5、例子

s = "I Love Python."
print(s.index('Love'))
print('I love python'.capitalize())
print(s.center(50,'-'))
print('3.68'.isdigit())
print('3'.isdigit())
print('3.68'.isnumeric())
print(' '.join('Iloveyou'))
print(' '.join(['I','Love','Python']))

# 2
# I love python
# ------------------I Love Python.------------------
# False
# True
# False
# I l o v e y o u
# I Love Python
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值