Python3.6.4的str的源代码

在Python的IDE工具pycharm中可以输入数据类型的名称后,ctrl + B,数据类型的源代码。str的部分源代码如下:

str类的方法

capitailize:字符串的首字母大写

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.

"""

return ""

方法实例:

test = "title"

v = test.capitalize()

print(v)

Title

```

casefold:将字符串全部转换为小写,不仅仅识别英文!

def casefold(self): # real signature unknown; restored from __doc__

"""

S.casefold() -> str

Return a version of S suitable for caseless comparisons.

"""

return ""

方法实例:

test = "Case One"

v = test.casefold()

print(v)

case one

```

center:已制定长度将字符串居中,并可调整填充字符(默认空格)

def center(self, width, fillchar=None): # real signature unknown; restored from __doc__

"""

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)

"""

return ""

用法实例:

test = "test"

v = test.center(20,"-")

print(v)

--------test--------

```

ljust:设定字符串的长度,并以指定填充符对字符串进行左对齐

def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__

"""

S.ljust(width[, fillchar]) -> str

Return S left-justified in a Unicode string of length width. Padding is

done using the specified fill character (default is a space).

"""

return ""

用法实例

string = "test"

print(string.ljust(20,"-"))

test----------------

```

rjust:设定字符串的长度,并以指定填充符对字符串进行右对齐

def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__

"""

S.rjust(width[, fillchar]) -> str

Return S right-justified in a string of length width. Padding is

done using the specified fill character (default is a space).

"""

return ""

用法实例

string = "test"

print(string.rjust(20,"-"))

----------------test

```

zfill:设定字符串的长度,并以数字“0”对字符串进行右对齐

def zfill(self, width): # real signature unknown; restored from __doc__

"""

S.zfill(width) -> str

Pad a numeric string S with zeros on the left, to fill a field

of the specified width. The string S is never truncated.

"""

return ""

用法实例

string = "test"

print(string.zfill(20))

0000000000000000test

```

count:计算字符串中制定的字符出现的次数,可定义查找的范围。设定范围时注意查找的区间:左闭右开区间

def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__

"""

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.

"""

return 0

用法实例:

test = "high school student"

v1 = test.count("s")

v2 = test.count("s",0,12)

print(v1,v2,sep="\n")

2

1

8. endswith:判断字符串是否以指定字符结尾

```

def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__

"""

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.

"""

return False

```

用法实例:

```

>>> string = 'hello world'

>>> print(string.endswith("ld"))

True

```

9. startswith:判断字符串是否以指定字符开始

```

def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__

"""

B.startswith(prefix[, start[, end]]) -> bool

Return True if B starts with the specified prefix, False otherwise.

With optional start, test B beginning at that position.

With optional end, stop comparing B at that position.

prefix can also be a tuple of bytes to try.

"""

return False

```

用法实例

```

>>> string = 'hello world'

>>> print(string.startswith("hi"))

False

```

10. expandtabs:已指定长度对字符串进行对齐。常用于制表

```

def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__

"""

B.expandtabs(tabsize=8) -> copy of B

Return a copy of B where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

"""

pass

```

用法实例

```

>>> string = '1234567\t89'

>>> print(string.expandtabs(6))

1234567 89

```

在上面的例子中,expandtabs的作用是:对字符串的内容每6个检查一次,如果6个字符中没有出现制表符tab,则不做任何操作,继续往下1个6个字符继续查找。数字“7”后后面出现\t,则这里\t表示5个空格。

```

>>> string = 'username\tage\tweight\nliu\t21\t59kg\nhao\t23\t62kg\nhai\t23\t59kg'

>>> print(string.expandtabs(20))

username age weight

liu 21 59kg

hao 23 62kg

hai 23 59kg

```

11. find:从左往右,查找指定字符在字符串中第一次出现的位置(下标)。同样区间范围是左开右闭

```

def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__

"""

B.find(sub[, start[, end]]) -> int

Return the lowest index in B where subsection sub is found,

such that sub is contained within B[start,end]. Optional

arguments start and end are interpreted as in slice notation.

Return -1 on failure.

"""

return 0

```

用法实例

```

>>> string = "asdfuioas"

>>> l = len(string)

>>> s1 = string.find("a")

>>> s2 = string.find("a",7)

>>> s3 = string.find("x")

>>> print(s1,s2,s3)

0 7 -1

```

其中,s2表示从下标7开始查找。如果在字符串中没有找对指定的字符,其返回值为“-1”。

12. index:功能和find相同,但是如果在字符串中没有找对指定的字符,会报错。一般常使用find

```

>>> string = "asdfuioas"

>>> print(string.index("x"))

Traceback (most recent call last):

File "", line 1, in

ValueError: substring not found

```

13. format:将一个字符串中的占位符替换成指定的字符

```

def format(self, *args, **kwargs): # known special case of str.format

"""

S.format(*args, **kwargs) -> str

Return a formatted version of S, using substitutions from args and kwargs.

The substitutions are identified by braces ('{' and '}').

"""

pass

```

用法实例

```

>>> string = "I am {name},I am {age} year old"

>>> print(string.format(name="haoahai",age=24))

I am haoahai,I am 24 year old

>>> string = "I am {0},I am {1} year old"

>>> print(string.format("haoahai",24))

I am haoahai,I am 24 year old

>>> string = "I am {name},I am {age} year old"

>>> print(string.format(**{"name":"haohai","age":24}))

I am haohai,I am 24 year old

```

在看到类的方法中,如果参数中出现“**”,表示可以使用字典形式。

14. format_map:功能和format一致,参数使用字典的形式

```

def format_map(self, mapping): # real signature unknown; restored from __doc__

"""

S.format_map(mapping) -> str

Return a formatted version of S, using substitutions from mapping.

The substitutions are identified by braces ('{' and '}').

"""

return ""

```

用法实例

```

>>> string = "I am {name},I am {age} year old"

>>> print(string.format_map({"name":"haohai","age":24}))

I am haohai,I am 24 year old

```

15. isalnum:判断字符串中是否只包含数字字母

```

def isalnum(self): # real signature unknown; restored from __doc__

"""

S.isalnum() -> bool

Return True if all characters in S are alphanumeric

and there is at least one character in S, False otherwise.

"""

return False

```

用法实例

```

>>> string = "lhh1410_"

>>> print(string.isalnum())

False

```

16. isalpha:判断字符串中是否只包含字母

```

def isalpha(self): # real signature unknown; restored from __doc__

"""

S.isalpha() -> bool

Return True if all characters in S are alphabetic

and there is at least one character in S, False otherwise.

"""

return False

```

用法实例

```

>>> print(string.isalpha())

False

```

17. isdecimal:判断字符串中是否只包含数字(只能识别是否为十进制数字)

```

def isdecimal(self): # real signature unknown; restored from __doc__

"""

S.isdecimal() -> bool

Return True if there are only decimal characters in S,

False otherwise.

"""

return False

```

用法实例

```

>>> string1 = "123"

>>> string2 = "②"

>>> print(string1.isdecimal(),string2.isdecimal(),sep="\n")

True

False

```

18. isdigit:判断字符串中是否只包含数字,可识别特殊数字

```

def isdigit(self): # real signature unknown; restored from __doc__

"""

S.isdigit() -> bool

Return True if all characters in S are digits

and there is at least one character in S, False otherwise.

"""

return False

```

用法实例

```

>>> string2 = "②"

>>> print(string2.isdecimal(),string2.isdigit(),sep="\n")

False

True

```

19. isnumeric:判断字符串中是否只包含数字,可识别中文数字

```

def isnumeric(self): # real signature unknown; restored from __doc__

"""

S.isnumeric() -> bool

Return True if there are only numeric characters in S,

False otherwise.

"""

return False

```

用法实例

```

>>> string = "二"

>>> print(string.isdigit(),string.isnumeric())

False True

```

当我们在判断一个文件中的中文几级标题时,可以利用decimal和digit的判断是False并且isnumeric是True时来一起判定中文的标题

20. isidentifier:判断字符串是否为标识符(即是否有字母、数字和下划线组成)

```

def isidentifier(self): # real signature unknown; restored from __doc__

"""

S.isidentifier() -> bool

Return True if S is a valid identifier according

to the language definition.

Use keyword.iskeyword() to test for reserved identifiers

such as "def" and "class".

"""

return False

```

用法实例

```

>>> string1 = "0jump"

>>> string2 = "_0jump"

>>> print(string1.isidentifier(),string2.isidentifier())

False True

```

21. isprintable:判断字符串中是否存在“不可显示“的字符

```

def isprintable(self): # real signature unknown; restored from __doc__

"""

S.isprintable() -> bool

Return True if all characters in S are considered

printable in repr() or S is empty, False otherwise.

"""

return False

```

用法实例

```

>>> string = "1234567\t98"

>>> print(string.isprintable())

False

```

22. isspace:判断字符串中是否只存在空格

```

def isspace(self): # real signature unknown; restored from __doc__

"""

S.isspace() -> bool

Return True if all characters in S are whitespace

and there is at least one character in S, False otherwise.

"""

return False

```

用法实例

```

>>> string1 = "hao hai"

>>> string2 = " "

>>> print(string1.isspace(),string2.isspace())

False True

```

23. islower:判断字符串中 **字母** 是否全部为小写

```

def islower(self): # real signature unknown; restored from __doc__

"""

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.

"""

return False

```

用法实例

```

>>> string = "@-=+liu"

>>> print(string.islower())

True

```

24. lower:将字符串中的字母转换成小写

```

def lower(self): # real signature unknown; restored from __doc__

"""

S.lower() -> str

Return a copy of the string S converted to lowercase.

"""

return ""

```

用法实例

```

>>> string = "Hurst_Liu"

>>> print(string.lower())

hurst_liu

```

25. isupper:判断字符串中的字母是否全部为大写

```

def isupper(self): # real signature unknown; restored from __doc__

"""

B.isupper() -> bool

Return True if all cased characters in B are uppercase and there is

at least one cased character in B, False otherwise.

"""

return False

```

用法实例

```

>>> string = "HURST_"

>>> print(string.isupper())

True

```

26. upper:将字符串中的字母全部转换为大写

```

def upper(self): # real signature unknown; restored from __doc__

"""

S.upper() -> str

Return a copy of S converted to uppercase.

"""

return ""

```

用法实例

```

>>> string = "hurst_"

>>> print(string.upper())

HURST_

```

27. istitle:判断字符串是否为英文标题

```

def istitle(self): # real signature unknown; restored from __doc__

"""

B.istitle() -> bool

Return True if B is a titlecased string and there is at least one

character in B, i.e. uppercase characters may only follow uncased

characters and lowercase characters only cased ones. Return False

otherwise.

"""

return False

```

用法实例

```

>>> string = "it's a good man"

>>> print(string.istitle())

False

```

28. title:将字符串转换成英文标题的形式(首字母大写)

```

def title(self): # real signature unknown; restored from __doc__

"""

B.title() -> copy of B

Return a titlecased version of B, i.e. ASCII words start with uppercase

characters, all remaining cased characters have lowercase.

"""

pass

```

用法实例

```

>>> string = "it's a good man"

>>> print(string.title())

It'S A Good Man

```

29. join:将字符串中的每一个元素按照指定字符进行填充

```

def join(self, iterable): # real signature unknown; restored from __doc__

"""

S.join(iterable) -> str

Return a string which is the concatenation of the strings in the

iterable. The separator between elements is S.

"""

return ""

```

用法实例

```

>>> string = "nospace"

>>> print(" ".join(string))

n o s p a c e

>>> print("-".join(string))

n-o-s-p-a-c-e

```

30. strip:默认去除字符串左右2边的空格,可指定去除的字符

```

def strip(self, *args, **kwargs): # real signature unknown

"""

Strip leading and trailing bytes contained in the argument.

If the argument is omitted or None, strip leading and trailing ASCII whitespace.

"""

pass

```

用法实例

```

>>> string = " test "

>>> print(string.strip())

test

```

31. ltrip:默认去除字符串左边的空格,可指定去除的字符

```

def lstrip(self, chars=None): # real signature unknown; restored from __doc__

"""

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.

"""

return ""

```

用法实例

```

>>> print(string.lstrip())

test

```

32. rstrip:默认去除字符串左右2边的空格,可指定去除的字符

```

def rstrip(self, chars=None): # real signature unknown; restored from __doc__

"""

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.

"""

return ""

```

用法实例

```

>>> string = " test "

>>> print(string.rstrip())

test

```

33. translate:和maketrans配合使用。将字符串中的字符替换成指定字符(一对一替换,并非整体替换)

```

def translate(self, table): # real signature unknown; restored from __doc__

"""

S.translate(table) -> str

Return a copy of the string S in which each character has been mapped

through the given translation table. The table must implement

lookup/indexing via __getitem__, for instance a dictionary or list,

mapping Unicode ordinals to Unicode ordinals, strings, or None. If

this operation raises LookupError, the character is left untouched.

Characters mapped to None are deleted.

"""

return ""

```

用法实例

```

>>> string = "asdljdlfadfd"

>>> m = string.maketrans("asd",123)

Traceback (most recent call last):

File "", line 1, in

TypeError: maketrans() argument 2 must be str, not int

>>> m = string.maketrans("asd","123")

>>> new_string = string.translate(m)

>>> print(new_string)

123lj3lf13f3

```

34. replace:将字符串中的字符替换成指定字符(整体替换)

```

def _replace(self, **kwargs):

'Return a new named tuple object replacing specified fields with new values.'

return self

```

用法实例

```

>>> string = "asd;a1s2d1"

>>> print(string.replace("asd","123"))

123;a1s2d1

```

35. split:从左开始,将字符串按照指定分隔符分割为指定部分(不包含分隔符)

```

def splitlines(self, keepends=None): # real signature unknown; restored from __doc__

"""

S.splitlines([keepends]) -> list of strings

Return a list of the lines in S, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends

is given and true.

"""

return []

```

用法实例

```

>>> string = "asdyouarsd0s23"

>>> print(string.split("s"))

['a', 'dyouar', 'd0', '23']

>>> print(string.split("s",2))

['a', 'dyouar', 'd0s23']

```

36. partition:将字符串按照指定分隔符分割成3部分,包含分隔符(当有多个分隔符时,从左往右去第一个分隔符)

```

def partition(self, *args, **kwargs): # real signature unknown

"""

Partition the bytearray into three parts using the given separator.

This will search for the separator sep in the bytearray. If the separator is

found, returns a 3-tuple containing the part before the separator, the

separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original

bytearray object and two empty bytearray objects.

"""

pass

```

用法实例

```

>>> string = "asdyouarsd0s23"

>>> print(string.partition("s"))

('a', 's', 'dyouarsd0s23')

```

# str类的通用功能

1. 索引:通过元素的下标,来提取字符串中的元素(子串)。

```

>>> string = "learning python"

>>> print(len(string),string[2])

15 a

```

通过索引的方式可以实现字符串元素的读取操作,但由于字符串的元素是存储在连续的内存地址空间中,通过索引是无法实现字符串的修改。**一旦字符串被拼接、修改后,系统会重新开辟内存地址来存放新的字符串**

```

>>> string = "learning python"

>>> string[2] = "sd"

Traceback (most recent call last):

File "", line 1, in

TypeError: 'str' object does not support item assignment

```

2. 切片:提取字符串中下标连续的子序列

```

>>> string = "learning python"

>>> print(string[0:6],string[0:-1],sep="\n")

learni

learning pytho

```

“-1”表示为字符串的最后一个下标(注意右开区间的问题)

3. 长度len:计算字符串的长度,即元素的个数

```

>>> string = "learning python"

>>> print(len(string))

15

```

**注意:如果是Python3.6,len表示为元素个数;如果是Python2.7,则是字符传所占的字节数**

4. range:创建连续的序列(数字)

```

>>> ran = range(1,10)

>>> print(ran)

range(1, 10)

```

如果是Python2.7中,上述的结果会直接显示1~10这个数字,即为所有的数字序列立即分配内容地址。Python3.6有所不同,只有在正式调用时才会为子序列开辟内存空间。

range常和len配合使用,用来提取字符串(str类创建的对象)的每一个元素即元素对应的下标

```

string = "python"

l = len(string)

r = range(0,l)

for i in r :

print(i,string[i])

0 p

1 y

2 t

3 h

4 o

5 n

```

5. for、while:提取字符串中的每一个元素

```

string = "python"

for i in string :

print(i)

l = len(string)

num = 0

while num < l :

print(num,string[num])

num += 1

p

y

t

h

o

n

0 p

1 y

2 t

3 h

4 o

5 n

```

hurst代码 python_python数据类型—字符串相关推荐

  1. python核心数据类型_Python核心数据类型——字符串

    字符串 Python的字符串是一个有序的字符集合,有序指的是可以通过偏移来访问每个字符,每个字符有严格的从左到右的位置顺序,类似于数组.Python中没有单个字符的类型(C语言中的char),取而代之 ...

  2. Python学习教程:数据类型—字符串大总结

    Python学习教程:数据类型-字符串大总结 1. Python字符串的创建 字符串是Python中最常见的数据类型,通常使用单引号或双引号来定义一个字符串,如下: str = "我是字符串 ...

  3. 前端面试:手写代码JS实现字符串反转

    前端萌新面试:手写代码JS实现字符串反转 前言 因为做前年小红书的前端校招面试题,发现出现好几道关于字符串对象和数组对象的题目,说难不难,但突然要写的话一时想不起来,这不想着做个小总结. 首先明白字符 ...

  4. 编程笔试(解析及代码实现):字符串反转(字符串逆序输出)代码实现十多种方法对比(解析思路及其耗费时间)详细攻略

    编程笔试(解析及代码实现):字符串反转(字符串逆序输出)代码实现十多种方法对比(解析思路及其耗费时间)详细攻略 目录 字符串反转(字符串逆序输出)代码实现十多种方法对比(解析思路及其耗费时间)详细攻略 ...

  5. python中object是什么数据类型_自学Python2.1-基本数据类型-字符串str(object) 上

    自学Python2.1-基本数据类型-字符串str(object) 上 字符串是 Python 中最常用的数据类型.我们可以使用引号('或")来创建字符串. 创建字符串很简单,只要为变量分配 ...

  6. ( 4 )MySQL中的数据类型(字符串类型)

    MySQL中的数据类型(字符串类型) 字符长类型 六中数据库中的数据类型 char , varchar , text ,blob,enum,set char和varchar char定长:磁盘空间比较 ...

  7. 数据类型-字符串(str)

    数据类型-字符串(str) 文章目录 数据类型-字符串(str) 1.字符串的定义方法 2.字符串的特性 - 索引 - 切片 - 重复 - 连接 - 成员操作符 - for循环遍历 - 枚举 - zi ...

  8. python数据字符串_python数据类型-字符串

    数据类型-字符串: 特性:有序和不可变 字符串可以加和乘 拼接 创建: 对于字符串,一下表示: s.capitalize()开头大写其余小写 'Helloworld!' s.casefold()全部小 ...

  9. php将sql语句识别成字符串,ASP_把字符串转换成数据库SQL语句格式,复制代码 代码如下:'把字符串 - phpStudy...

    把字符串转换成数据库SQL语句格式 复制代码 代码如下: '把字符串转换成数据库SQL语句格式 '------------------------------------------------- F ...

最新文章

  1. 通过Python的__slots__节省9GB内存
  2. oracle怎么捕获表上的DML语句(不包括select)语句)
  3. 贪吃蛇程序 php,php Web程序 - 贪吃蛇学院-专业IT技术平台
  4. python api是什么_python – 如何处理API响应
  5. python的pandas库中如何计算每列出现最多的值_Python Pandas:计算多个列的每个唯一值的显示次数...
  6. bread是可数还是不可数_可数名词不可数名词分不清?出题老师告诉你方法
  7. OPPO Reno6系列新机获3C认证:支持5G 标配65W快充
  8. 查oracle执行的sql,oracle查询正在执行的sql
  9. keepalived+Nginx实现Web高可用
  10. python零基础能学吗-Python真的零基础可以学会吗?
  11. 3.3 决策树分类与回归实战
  12. android中的Handler和Callback机制
  13. T - 取石子游戏 HDU - 1527(威佐夫博弈)
  14. Windows小技巧 – Win+R提高Windows使用效率
  15. 小米HTML查看器记住密码,小米路由器 SSH 密码计算工具,开启小米SSH访问
  16. wifi服务器延迟高,网络延时高(网络延迟高怎么办(家里WIFI延迟高,教你几招搞定网络延迟))...
  17. 【C++程序设计技巧】NVI(Non-Virtual Interface )
  18. 千万别把WIFI玩坏了!关于WIFI的新鲜玩法和商业模式探讨
  19. 怎么用计算机隐藏应用程序,win7 隐藏应用程序 电脑如何隐藏程序_win7教程_uc电脑园...
  20. Docker--容器挂载

热门文章

  1. Linux常见面试题2
  2. 如何在页面调用JS函数的代码
  3. python SSL error: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) 解决方法
  4. Restful与webService区别
  5. golang go build 报错 import cycle not allowed
  6. centos7 yum 安装 python3
  7. Docker报错 WARNING: IPv4 forwarding is disabled. Networking will not work.
  8. Android中/system/build.prop文件解读
  9. 如何使用Rebase以及bind来重定位和绑定dll
  10. Android 中 JUnit 测试的配置