Python数据类型之字符串

in 互联网技术 with 0 comment  访问: 261 次

字符串定义和创建

字符串是由字符组成的序列,是一个有序的字符的集合,用于存储和表示基本的文本信息,''" "''' '''中间包含的内容称之为字符串。

而且Python的字符串类型是不可以改变的,你无法将原字符串进行修改,但是可以将字符串的一部分复制到新的字符串中,来达到相同的修改效果。

创建示例如下:

单引号:

>>> string = 'hello'
>>> type(string)
<class 'str'>

双引号:

>>> string = "hello"
>>> type(string)
<class 'str'>

三引号:

>>> string = '''hello'''
>>> type(string)
<class 'str'>

>>> string = """hello"""
>>> type(string)
<class 'str'>

指定类型:

>>> string = str("hello")
>>> type(string)
<class 'str'>

字符串的特性与常用方法

特性:按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序
15281226254407.jpg

补充:

字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如site = r'jike\tfm', unicode字符串与r连用必需在r前面。

urb解释参考:https://blog.csdn.net/u010496169/article/details/70045895

字符串转义字符含义如下:

符号 说明
\' 单引号
\ " 双引号
\a 发出系统响铃声
\b 退格符
\n 换行符
\t 横向制表符(Tab)
\v 纵向制表符
\r 回车符
\f 换页符
\o 八进制数代表的字符
\x 十六进制数代表的字符
\0 表示一个空字符
\ 反斜杠

字符串常用方法

每个类的方法其实都是很多的,无论我们在学习的过程中个还是工作的时候,其实常用的没有多少,所以我们没必都记住,可以通过看源代码然后再借助搜索引擎去了解你所需要的,这里介绍给你加深点印象。

索引和切片

index: 返回某个字符在字符串中的索引位置

def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0
参数 描述
str 指定检索的字符串
start 开始索引,默认为0
end 结束索引,默认为字符串的长度
>>> name = 'nock'
>>> name[0];name[1]
'n'
'o'
>>> name.index('n')
0
>>> name.index('c', 0, 4)
2

切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。注意这与你使用的索引操作符十分相似。记住数是可选的,而冒号是必须的,切片操作符中的第一个数表示切片开始的位置,第二个数表示切片到哪里结束,第三个数表示切片间隔数。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。注意,返回的序列从开始位置开始 ,刚好在结束位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。

>>> name = 'nockgod'
>>> name[0:7]
'nockgod'
>>> name[0:4]
'nock'
>>> name[:7]
'nockgod'
>>> name[:]
'nockgod'
>>> name[0:7:2]
'ncgd'
>>> name[::2]
'ncgd'
>>> name[::-1]
'dogkcon'

切片符说明:

切片符 说明
[:] 提取从开头到结尾的整个字符串
[start:] 从start到结尾的字符串
[:end] 从开头提取到end - 1
[start:end] 从start提取到end - 1
[start : end : setp] 从start提取到end-1,每setp个字符提取一个 setp步长值

索引和切片同时适用于字符串、列表与元组:

实例:

# 定义一个列表,列表内有三个元素
>>> var=["PM","OPS","DEV"]
# 通过索引取到了一个值
>>> var[0]
'PM'
# 通过切片取到了多个值
>>> var[0:2]
['PM', 'OPS']
>>> var[1:3]
['OPS', 'DEV']

查找

find: 查找一个字符或字符组合在一个字符串中的索引位置,索引位置从0开始,而且找到了第一个就不会往下找了,字符串可以根据索引进行切片

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
参数 描述
str 指定检索的字符串
start 开始索引,默认为0
end 结束索引,默认为字符串的长度
>>> msg = "My blog address is fashengba.com"
>>> msg.find("blog")
3
>>> msg.find("b")             # 找到第一个b的索引值,就不往下找了
3
>>> msg.find("b", 8, 30)
26

rfind: 查找一个字符串中某个字符所在的索引,如果这个字符串中有多个这个字符,那么会找到最右边的那个字符

def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        B.rfind(sub[, start[, end]]) -> int

        Return the highest 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
参数 描述
str 查找的字符串
start 开始查找的位置,默认为0
end 结束查找位置,默认为字符串的长度
>>> msg = "My blog address is fashengba.com"
>>> msg.rfind('b')
26
>>> msg.rfind('b', 1, 10)
3
>>> print('find nock ok') if msg.rfind('nock') != -1 else print('find nock failed')
find nock failed

rindex: 跟rfind差不多

def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        B.rindex(sub[, start[, end]]) -> int

        Like B.rfind() but raise ValueError when the substring is not found.
        """
        return 0
参数 描述
str 查找的字符串
start 开始查找的位置,默认为0
end 结束查找位置,默认为字符串的长度
>>> msg = "My blog address is fashengba.com"
>>> msg.rindex('b')
26
>>> msg.rindex('b', 1, 10)
3
>>> print('find nock ok') if msg.rindex('nock') != -1 else print('find nock failed')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    print('find nock ok') if msg.rindex('nock') != -1 else print('find nock failed')
ValueError: substring not found

rindex跟rfind不同的是当你要查询的字符串不存在的时候会报ValueError: substring not found的提示,而rfind和find则找不到的时候都会返回-1。

移除空白

rstrip : 去掉右边的空格以及tab制表符

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 ""
>>> msg1 = "   My blog address is fashengba.com   "
>>> msg2 = "***My blog address is fashengba.com***"
>>> msg1.rstrip(); msg2.rstrip('*')
'   My blog address is fashengba.com'
'***My blog address is fashengba.com'

lstrip : 去掉左边的空格以及tab制表符

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 ""
>>> msg1 = "   My blog address is fashengba.com   "
>>> msg2 = "***My blog address is fashengba.com***"
>>> msg1.lstrip(); msg2.lstrip('*')
'My blog address is fashengba.com   '
'My blog address is fashengba.com***'

strip : 去掉字符串左右两边的空格以及tab制表符换行

def strip(self, chars=None): # real signature unknown; restored from __doc__
        """
        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.
        """
        return ""
>>> msg1 = "   My blog address is fashengba.com   "
>>> msg2 = "***My blog address is fashengba.com***"
>>> msg1.strip(); msg2.strip('*')
'My blog address is fashengba.com'
'My blog address is fashengba.com'

分割

splitlines 使用回车符进行字符串分片,最后得到一个列表

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 []
>>> msg = "nock\ngod"
>>> msg
'nock\ngod'
>>> msg.splitlines()
['nock', 'god']
>>> msg = """my
... name
... is
... nock"""
>>> msg.splitlines()
['my', 'name', 'is', 'nock']

rsplit : 是从右开始切片,当不指定从哪个分隔符数开始,默认和split没有区别,但是指定了从第几个分隔符之后,就会有所不同了

def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings

        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return []
参数 描述
str 分隔符,默认为空格
num 分割次数
>>> msg = "my name is nock name is nock name is nock"
>>> msg.rsplit('name')
['my ', ' is nock ', ' is nock ', ' is nock']
>>> msg.rsplit('name', 2)
['my name is nock ', ' is nock ', ' is nock']

split : 使用指定分隔符对字符串进行分割,最后得到一个列表

def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        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.
        """
        return []
>>> msg = "my name is nock name is nock name is nock"
>>> msg.split()
['my', 'name', 'is', 'nock', 'name', 'is', 'nock', 'name', 'is', 'nock']
>>> msg.split('name')
['my ', ' is nock ', ' is nock ', ' is nock']

长度补全

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 ""
参数 描述
width 指定字符串长度
fillchar 填充字符,默认为空格
>>> name = 'nock'
>>> name.ljust(10, 'G')
'nockGGGGGG'

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 ""
参数 描述
width 指定填充指定字符后中字符串的总长度
fillchar 填充的字符,默认为空格
>>> name = 'nock'
>>> name.rjust(10, 'G')
'GGGGGGnock'

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 ""
>>> name = 'nock'
>>> name.zfill(10)
'000000nock'

大小写

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.
        """
        return ""
>>> name = 'nock'
>>> name.capitalize()
'Nock'

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
>>> name1 = 'nock'
>>> name2 = 'Nockgod'
>>> name1.islower()
True
>>> name2.islower()
False

istitle : 判断一个字符串是否为title,字符串首字母大写就为title,返回时布尔值

def istitle(self): # real signature unknown; restored from __doc__
        """
        S.istitle() -> bool

        Return True if S is a titlecased string and there is at least one
        character in S, i.e. upper- and titlecase characters may only
        follow uncased characters and lowercase characters only cased ones.
        Return False otherwise.
        """
        return False
>>> name = 'lol'
>>> name.istitle()
False
>>> name = 'I Love Lol'
>>> name.istitle()
True

isupper : 判断字符串是否为全部大写,返回布尔值

def isupper(self): # real signature unknown; restored from __doc__
        """
        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.
        """
        return False
>>> name1.isupper(), name2.isupper(), name3.isupper()
(False, True, True)

upper : 把字符串都变换为大写

def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str

        Return a copy of S converted to uppercase.
        """
        return ""
>>> name = 'nock'
>>> name.upper()
'NOCK'

lower : 把所有的字符串都变为小写

def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str

        Return a copy of the string S converted to lowercase.
        """
        return ""
>>> name = 'NOCK'
>>> name.lower()
'nock'

swapcase : 大小写互换

def swapcase(self): # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str

        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""
>>> name = "My Name Is Nock"
>>> name.swapcase()
'mY nAME iS nOCK'

判断

isalnum : 判断这个字符串是否单单由阿拉伯字母和数字组成,返回布尔值

def isalnum(self): # real signature unknown; restored from __doc__
        """
        B.isalnum() -> bool

        Return True if all characters in B are alphanumeric
        and there is at least one character in B, False otherwise.
        """
        return False
>>> name = 'nock 123 ^ff'
>>> name1 = '123 ^&&&'
>>> name2 = '123nock'
>>> name.isalnum(), name1.isalnum(), name2.isalnum()
(False, False, True)

isalpha : 判断字符串是否由纯英文,包括大小字母,返回布尔值

def isalpha(self): # real signature unknown; restored from __doc__
        """
        B.isalpha() -> bool

        Return True if all characters in B are alphabetic
        and there is at least one character in B, False otherwise.
        """
        return False
>>> name = 'nock123'
>>> name1 = '$%^^&&'
>>> name2 = 'nock'
>>> name.isalpha(), name1.isalpha(), name2.isalpha()
(False, False, True)

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
>>> u = 'nock'
>>> p = '123'
>>> up = '123.8'
>>> u.isdigit(), p.isdigit(), up.isdigit()
(False, True, False)

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
>>> u = '123nock'
>>> p = '123.0'
>>> up = 'nock'
>>> u.isidentifier(), p.isidentifier(), up.isidentifier()
(False, False, True)

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
>>> up = '123'
>>> u = '123nock'
>>> p = '123.0'
>>> u.isnumeric(), p.isnumeric(), up.isnumeric()
(False, False, True)

isprintable : 如果字符串中有制表符\t,返回布尔值

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
>>> msg = 'My name is nock\t blog address is fashengba.com'
>>> print("no tabs") if msg.isprintable() else print("have tabs")
have tabs
>>> msg = 'My name is nock blog address is fashengba.com'
>>> print("no tabs") if msg.isprintable() else print("have tabs")
no tabs

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
>>> msg = 'nock'
>>> print('is space') if msg.isspace() else print('no space')
no space
>>> msg = 'my name is nock'
>>> print('is space') if msg.isspace() else print('no space')
no space
>>> msg = '  '
>>> print('is space') if msg.isspace() else print('no space')
is space

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
参数 描述
suffix 后缀,可能是一个字符串,或者也可能是寻找后缀的tuple
start 开始,切片从这里开始
end 结束,片到此为止
>>> email = 'nockgod@gmail.com'
>>> print('is Google Email') if email.endswith('gmail.com') else print('not Google Email')
is Google Email

expandtabs : 如果字符串中包含一个\t的字符,如果包含则把\t变成8个空格,当然也可以指定个数

def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str

        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""
参数 描述
tabsize 指定转换字符串中的 tab 符号(‘\t’)转为空格的字符数
>>> msg = 'LOL is\t Good Game'
>>> msg.expandtabs()
'LOL is   Good Game'
>>> msg.expandtabs(tabsize=1)
'LOL is  Good Game'
>>> msg.expandtabs(tabsize=0)
'LOL is Good Game'
>>> msg.expandtabs(10)
'LOL is     Good Game'

startswith : 判断以什么开头,返回布尔值

def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool

        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False
>>> email = 'nockgod@gmail.com'
>>> email.startswith('nock')
True
>>> email.startswith('o', 2, 4)
False
>>> email.startswith('c', 2, 4)
True

其他方法

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
参数 描述
sub 搜索的子字符串
start 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0;
end 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
>>> msg = 'my name is nock'
>>> msg.count('n')
2
>>> msg.count('n', 1, 10)
1
>>> msg.count('nock')
1

center : 美观打印,打印包括现有变量在内的30个字符串, 如果字符串不够实用相应的字符前后补全

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 ""
>>> annotation = "Shoping Info"
>>> annotation.center(50, '#')
'###################Shoping Info###################'

encond : 编码转换,在py3中把字符串转为二进制

def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes

        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""
>>> msg = '葫芦娃'
>>> msg.encode(encoding='utf-8', errors='strict')
b'\xe8\x91\xab\xe8\x8a\xa6\xe5\xa8\x83'

format : 这是一种文件格式化的输出,可以是变量值也可以是下标索引的方法

def format(*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

使用参考文章:Python格式化输出详解

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 ""
>>> msg = """ ################### Shoping List ###################
... book: {Book}
... bike: {Bike}
... food: {Food}"""
>>> print(msg.format_map({'Book': 39, 'Bike': 800, 'Food': 300}))
 ################### Shoping List ###################
book: 39
bike: 800
food: 300

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 ""
# 对序列进行操作(分别使用' '与':'作为分隔符)
>>> info = ['hello', 'world', 'Python', 'Coder']
>>> ' '.join(info)
'hello world Python Coder'
>>> ':'.join(info)
'hello:world:Python:Coder'

# 对字符串进行操作
>>> info = "hello world python coder"
>>> ':'.join(info)
'h:e:l:l:o: :w:o:r:l:d: :p:y:t:h:o:n: :c:o:d:e:r'

# 对元组进行操作
>>> info = ('hello', 'world', 'Python', 'Coder')
>>> ':'.join(info)
'hello:world:Python:Coder'

# 对字典操作 字典是无序的
>>> info = {'hello': 1, 'world': 2, 'python': 3, 'coder': 4}
>>> ':'.join(info)
'coder:hello:python:world'

# 合并目录
>>> import os
>>> os.path.join('/data/', 'www/web/', 'code')
'/data/www/web/code'

maketrans : 这个方法要配合translate方法使用,对数据进行加密/反解

def maketrans(self, [i]args, [/i]*kwargs): # real signature unknown
        """
        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.
        """
        pass
# 加密
>>> info = "10.0.1.100"
>>> mtinfo = info.maketrans('abcdefg', '3!@#$%^')
>>> mtinfo
{97: 51, 98: 33, 99: 64, 100: 35, 101: 36, 102: 37, 103: 94}

# 解密,打印出真实的info的值
>>> info.translate(mtinfo)
'10.0.1.100'

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 ""
>>> name = 'nock'
>>> name.maketrans('abcde', '12345')
{97: 49, 98: 50, 99: 51, 100: 52, 101: 53}
>>> cname = name.maketrans('abcde', '12345')
>>> name.translate(cname)
'no3k'

replace : 替换字符串字符,也可以指定替换的次数

def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str

        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""
参数 描述
old 将被替换的子字符串
new 新字符串,用于替换old子字符串
count 可选字符串, 替换不超过count次
>>> info = 'Pythog'
>>> info.replace('g', 'n')
'Python'
>>> info = 'Good'
>>> info.replace('o', 'e', 2)
'Geed'

title : 把一个字符串变为一个title,首字母大写

def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str

        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""
>>> info = 'shopping list'
>>> info.title()
'Shopping List'

到这里字符串的使用方法就介绍完了,基本上常用的都介绍了。

WeZan
Responses