Python字符串

字符串方法

>>> for i in dir(str):print(i)

capitalize 将字符串的第一个字符转换为大写

casefold 转换字符为小写,比lower()更强

center返回宽度 width ,字符串居中,两端填充fillchar的字符串

count返回指定字符串在字符串里出现的次数

encode 以指定的编码格式编码字符串

endswith判断字符串是否以指定后缀结尾

expandtabs把字符串中的 tab 符号\t转为空格

find检测字符串中是否包含子字符串,包含则返回subindex,不包含返回-1

format 格式化字符串

format_map 格式化字符串

index 检测字符串中是否包含子字符串,类似find,但是不包含会触发异常

isalnum判断字符串至少有一个字符并且所有字符都是字母或数字

isalpha判断字符串至少有一个字符并且所有字符都是字母或中文

isdecimal 判断字符串至少有一个字符并且所有字符都是unicode数字和全角数字

isdigit 判断字符串至少有一个字符并且所有字符都是半角数字、全角数字、字节数字

isidentifier用于判断字符串是否是有效的 Python 标识符

islower判断字符串中区分大小写的字符是否只存在小写字符

isnumeric 判断字符串至少有一个字符并且所有字符都是半角数字、全角数字、中文数字

isprintable 判断字符串中所有字符是否都是可打印字符

isspace判断字符串中是否只包含空白字符

istitle判断字符串是否是标题化的

isupper判断字符串中区分大小写的字符是否只存在大写字符

join将序列中的元素以指定的字符连接生成一个新的字符串

ljust返回长度为 width 的字符串,原字符串左对齐,后面填充fillchar

lower转换字符串中所有大写字符为小写

lstrip去掉字符串头的空白字符

maketrans创建字符映射的转换表,给translate用

partition返回由分隔符前,分隔符,分隔符后组成的元组

replace 替换字符串

rfind类似于 find()函数,不过是从右边开始查找

rindex类似于 index(),不过是从右边开始.

rjust 返回长度为 width 的字符串,原字符串右对齐,前面填充fillchar

rpartition类似partition,从右往左

rsplit 去掉字符串尾的空白字符

rstrip 去掉字符串尾的空白字符

split 按照给定的分隔符将字符串分隔为列表

splitlines 返回字符串中的行列表

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

strip 去掉字符串头和尾的空白字符

swapcase将字符串中大写转换为小写,小写转换为大写

title 将字符串标题化

translate根据转换表转换字符串

upper转换字符串中的小写字母为大写

zfill返回长度为 width 的字符串,原字符串右对齐,前面填充0

>>>

capitalize将字符串的第一个字符转换为大写

语法:

>>> help(str.capitalize)

Help on method_descriptor:

 

capitalize(...)

S.capitalize() -> str

 

Return a capitalized version of S, i.e. make the first character

have upper case and the rest lower case.

 

示例:

>>> s = 'hello world'

>>> s.capitalize()

'Hello world'

>>>

center/ljust/rjust/zfill/format/format_map格式化字符串

center 返回宽度 width 的字符串,原字符串居中,两端填充fillchar的字符串

fillchar默认为空格

语法:

>>> help(str.center)

Help on method_descriptor:

 

center(...)

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)

 

示例:

>>> s = 'hello world'

>>> s.center(30,'*')

'*********hello world**********'

ljust 返回长度为 width 的字符串,原字符串左对齐,后面填充fillchar

返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。

 

语法:

>>> help(str.ljust)

    

Help on method_descriptor:

 

ljust(...)

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).

 

示例:

>>> s = 'ab12'

    

>>> s.ljust(8,'*')

    

'ab12****'

rjust返回长度为 width 的字符串,原字符串右对齐,前面填充fillchar

语法:

>>> help(str.rjust)

    

Help on method_descriptor:

 

rjust(...)

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).

 

示例:

>>> s = 'ab12'

    

>>> s.rjust(8,'*')

    

'****ab12'

zfill 返回长度为 width 的字符串,原字符串右对齐,前面填充0

语法:

>>> help(str.zfill)

Help on method_descriptor:

 

zfill(...)

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.

 

示例:

>>> 'Ab12'.zfill()    #必须提供长度,不然报错

Traceback (most recent call last):

File "<pyshell#135>", line 1, in <module>

'Ab12'.zfill()

TypeError: zfill() takes exactly 1 argument (0 given)

>>> 'Ab12'.zfill(8)

'0000Ab12'

format 格式化字符串

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

语法:

>>> help(str.format)

Help on method_descriptor:

 

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 '}').

 

示例1:按位置格式化

>>> "{} {}".format("hello", "world")

'hello world'

>>> "{0} {1}".format("hello", "world")

'hello world'

>>> "{1} {0} {1}".format("hello", "world")

'world hello world'

 

示例2:按变量名格式化

>>> 'my name is {name},{age} years old'.format(name = 'bob',age = 18)

'my name is bob,18 years old'

 

>> D = {'name':'hh','age':18}

>>> 'my name is {name},{age} years old'.format(**D) #通过字典提供参数

'my name is hh,18 years old'

 

>>> 'my name is {0[0]},{0[1]} years old'.format(L) #通过列表提供参数

'my name is hh,18 years old'

format_map 类似format,参数是一个字典

语法:

>>> help(str.format_map)

Help on method_descriptor:

 

format_map(...)

S.format_map(mapping) -> str

 

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

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

 

示例:    

>>> 'my name is {name},{age} years old'.format_map({'name':'bob','age':18})

'my name is bob,18 years old'

 

count 返回指定字符串在字符串里出现的次数

在str[start:end]中查找sub出现的次数

语法:

>>> help(str.count)

Help on method_descriptor:

 

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.

 

示例:

>>> s = 'hello world'

>>> s.count('o')

2

>>> s.count('l')

3

>>> s.count('L')

0

>>> s.count('rl')

1

encode 以指定的编码格式编码字符串

返回bytes对象

默认编码方式为utf-8

 

语法:

>>> help(str.encode)

Help on method_descriptor:

 

encode(...)

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.

 

示例:

>>> s = 'hello world'

>>> s.encode('utf-8')

b'hello world'

>>> s1 = s.encode('utf-8')

>>> s1

b'hello world'

>>> type(s1)

<class 'bytes'>

 

>>> s = '你好'

>>> s.encode('utf-8')

b'\xe4\xbd\xa0\xe5\xa5\xbd'

>>> s.encode('utf-8').decode()

'你好'

endswith 判断字符串是否以指定后缀结尾

返回bool对象

 

语法:

 

>>> help(str.endswith)

Help on method_descriptor:

 

endswith(...)

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.

 

示例:

>>> s = 'hello world'

>>> s.endswith('ld')

True

>>> s.endswith('d')

True

>>> s.endswith('lo',1,4)

False

>>> s.endswith('lo',1,5)

True

expandtabs 把字符串中的 tab 符号\t转为空格

默认\t转换为8个空格

 

语法:

>>> help(str.expandtabs)

Help on method_descriptor:

 

expandtabs(...)

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.

 

示例:

>>> s = 'hello\tworld'

>>> print(s)

hello    world

>>> s.expandtabs()

'hello world'

>>> s

'hello\tworld'

>>> s.expandtabs(tabsize=1)

'hello world'

 

 

 

index/rindex/find/rfind查找字符串中的子字符串

index 检测字符串中是否包含子字符串

类似find,但是不包含会触发异常

语法:

>>> help(str.index)

Help on method_descriptor:

 

index(...)

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.

 

示例:

>>> s = 'hello world'

>>> s.index('ll')

2

>>> s.index('xx')

Traceback (most recent call last):

File "<pyshell#58>", line 1, in <module>

s.index('xx')

ValueError: substring not found

rindex 类似于 index(),不过是从右边开始.

find 检测 str 是否包含在字符串中

在str[start,end]中查找sub字符串,如果可以找到返回sub的最小index,否则返回-1

语法:

>>> help(str.find)

Help on method_descriptor:

 

find(...)

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.

 

示例:

>>> s = 'hello world'

>>> s.find('rl')

8

>>> s.find('l')

2

>>> s.find('la') #找不到返回-1

-1

rfind 类似于 find()函数,不过是从右边开始查找

在str[start,end]中查找sub字符串,如果可以找到返回sub的最大index,否则返回-1

 

语法:

>>> help(str.rfind)

Help on method_descriptor:

 

rfind(...)

S.rfind(sub[, start[, end]]) -> int

 

Return the highest 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.

 

示例:

>>> s = 'hello world'

>>> s.find('l') #find从左开始找,返回第一个找到的index,即字符串中sub的最小index

2

>>> s.rfind('l') #rfind从右开始找,返回第一个找到的index,即字符串中sub的最大index

9

>>> s.rfind('la') #找不到返回-1

-1

 

isalnum/isalpha/isdecimal/isdigit/isnumeric判断字符串内容

isalnum 判断字符串至少有一个字符并且所有字符都是字母或数字

语法:

>>> help(str.isalnum)

Help on method_descriptor:

 

isalnum(...)

S.isalnum() -> bool

 

Return True if all characters in S are alphanumeric(字母数字)

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

 

示例:

>>> ''.isalnum()

False

>>> 'ab12'.isalnum()

True

>>> 'ab@12'.isalnum()

False

>>> 'ab12你好'.isalnum()

True

isalpha 判断字符串至少有一个字符并且所有字符都是字母或中文

语法:

>>> help(str.isalpha)

Help on method_descriptor:

 

isalpha(...)

S.isalpha() -> bool

 

Return True if all characters in S are alphabetic

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

示例:

>>> ''.isalpha()

False

>>> 'ab'.isalpha()

True

>>> 'ab12'.isalpha()

False

>>> 'ab你好'.isalpha()

True

>>> 'ab@12'.isalpha()

False

isdecimal判断字符串至少有一个字符并且所有字符都是10进制数字

数字表示有以下几种:

  • unicodde数字(半角数字),英文输入模式下的数字0-9
  • 全角数字,中文输入模式下的数字0-9
  • 中文数字,零一二十百千万
  • 罗马数字,ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅪ
  • byte数字

 

unicode数字(半角数字)和全角数字为true

语法:

>>> help(str.isdecimal)

Help on method_descriptor:

 

isdecimal(...)

S.isdecimal() -> bool

 

Return True if there are only decimal(十进制) characters in S,

False otherwise.

示例:

>>> ''.isdecimal()

False

>>> '12'.isdecimal() #半角或全角数字true

True

>>> '12.3'.isdecimal() #浮点数false

False

>>> '五'.isdecimal() #中文数字false

False

>>> 'Ⅳ'.isdecimal() #罗马数字false

False

>>> b'123'.isdecimal() #字节数字会报错

Traceback (most recent call last):

File "<pyshell#95>", line 1, in <module>

b'123'.isdecimal()

AttributeError: 'bytes' object has no attribute 'isdecimal'

isdigit判断字符串至少有一个字符且所有字符都是数字

半角数字、全角数字、字节数字为true

 

语法:

>>> help(str.isdigit)

Help on method_descriptor:

 

isdigit(...)

S.isdigit() -> bool

 

Return True if all characters in S are digits(数字)

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

 

示例:

>>> '12'.isdigit() #半角或全角数字true

True

>>> '12.3'.isdigit() #浮点数false

False

>>> '五'.isdigit() #中文数字false

False

>>> 'Ⅳ'.isdigit()    #罗马数字false

False

>>> b'12'.isdigit()     #字节数字True

True

isnumeric判断字符串至少有一个字符并且所有字符都是数字字符

半角数字、全角数字、中文数字为true

 

语法:

>>> help(str.isnumeric)

Help on method_descriptor:

 

isnumeric(...)

S.isnumeric() -> bool

 

Return True if there are only numeric characters(数字字符) in S,

False otherwise.

 

示例:

>>> '12'.isnumeric()     #半角或全角数字true

True

>>> '12.3'.isnumeric()    #浮点数false

False

>>> '五'.isnumeric()     #中文数字true

True

>>> 'IV'.isnumeric()        #罗马数字false

False

>>> b'12'.isnumeric()    #字节数字会报错

Traceback (most recent call last):

File "<pyshell#112>", line 1, in <module>

b'12'.isnumeric()

AttributeError: 'bytes' object has no attribute 'isnumeric'

isidentifier 用于判断字符串是否是有效的 Python 标识符

可用来判断变量名是否合法

 

语法:

>>> help(str.isidentifier)

    

Help on method_descriptor:

 

isidentifier(...)

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".

 

示例1:

>>> 'a'.isidentifier()

True

>>> '12a'.isidentifier()     #变量名不能以数字开头

False

>>> 'def'.isidentifier()

True

 

示例2:keyword.iskeyword()查看python保留标识符

>>> import keyword

>>> keyword.iskeyword('a')

False

>>> keyword.iskeyword('def')

True

islower/isupper判断字符串中是否存在大写/小写字符

islower 判断字符串中区分大小写的字符是否只存在小写字符

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False

 

语法:

>>> help(str.islower)

Help on method_descriptor:

 

islower(...)

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.

 

示例:

>>> 'ab'.islower()

True

>>> 'ab12'.islower()

True

>>> 'aB12'.islower()

False

isupper 判断字符串中区分大小写的字符是否只存在大写字符

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False

 

语法:

>>> help(str.isupper)

Help on method_descriptor:

 

isupper(...)

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.

 

示例:

>>> 'AB'.isupper()

True

>>> 'AB12'.isupper()

True

>>> 'ABa'.isupper()

False

 

isprintable判断字符串中所有字符是否都是可打印字符。

 

 

语法:

>>> help(str.isprintable)

Help on method_descriptor:

 

isprintable(...)

S.isprintable() -> bool

 

Return True if all characters in S are considered

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

 

示例:    

>>> 'hello world'.isprintable()

True

>>> 'hello \t world'.isprintable()     #\t为不可打印字符

False

>>> ''.isprintable()

True

isspace 判断字符串中是否只包含空白字符

空白字符包括\t \n \r 空格等

 

语法:

>>> help(str.isspace)

    

Help on method_descriptor:

 

isspace(...)

S.isspace() -> bool

 

Return True if all characters in S are whitespace

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

 

示例:

>>> '\r\t\n '.isspace()

    

True

istitle/title 字符串标题化

istitle 如果字符串是标题化的则返回 True,否则返回 False

语法:

示例:

>>> s = 'hello world'

>>> s.istitle()

False

 

>>> s = 'Hello World'

>>> s.istitle()

True

 

title返回"标题化"的字符串

所有单词的首个字母转化为大写,其余字母均为小写

语法:

>>> help(str.title)

    

Help on method_descriptor:

 

title(...)

S.title() -> str

 

Return a titlecased version of S, i.e. words start with title case

characters, all remaining cased characters have lower case.

 

示例:

>>> s = 'hello world'

>>> s.title()

'Hello World'

 

join 将序列中的元素以指定的字符连接生成一个新的字符串

序列转字符串

语法:

>>> help(str.join)

    

Help on method_descriptor:

 

join(...)

S.join(iterable) -> str

 

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

iterable. The separator between elements is S.

 

示例:

>>> ''.join(['www','baidu','com']) #不指定分隔符

    

'wwwbaiducom'

>>> '.'.join(['www','baidu','com']) #指定分隔符

    

'www.baidu.com'

 

lower/casefold/upper/swapcase转换字符串大小写

lower 转换字符串中所有大写字符为小写

语法:

>>> help(str.lower)

Help on method_descriptor:

 

lower(...)

S.lower() -> str

 

Return a copy of the string S converted to lowercase.

 

示例:

>>> 'Ab12'.lower()

'ab12'

casefold 转换字符为小写

能将更多语言的字符转换为小写,在中英文下和lower()一样

 

语法:

>>> help(str.casefold)

    

Help on method_descriptor:

 

casefold(...)

S.casefold() -> str

 

Return a version of S suitable for caseless comparisons.

 

示例:

>>> s = 'ABcd'

    

>>> s.casefold()

    

'abcd'

 

upper转换字符串中的小写字母为大写

语法:

>>> help(str.upper)

Help on method_descriptor:

 

upper(...)

S.upper() -> str

 

Return a copy of S converted to uppercase.

 

示例:

>>> 'Ab12'.upper()

'AB12'

swapcase 将字符串中大写转换为小写,小写转换为大写

语法:

>>> help(str.swapcase)

    

Help on method_descriptor:

 

swapcase(...)

S.swapcase() -> str

 

Return a copy of S with uppercase characters converted to lowercase

and vice versa.

 

示例:

>>> s = 'ABcd'

    

>>> s.swapcase()

    

'abCD'

maketrans/translate创建转换表,转换字符串

maketrans 创建字符映射的转换表,给translate用

str.maketrans(intab, outtab)

 

示例:

>>> intab = 'ol'

>>> outtab = '*@'

>>> transtab = str.maketrans(intab,outtab) #创建转换表

>>> transtab

{111: 42, 108: 64}

>>> type(transtab)

<class 'dict'>

 

>>> 'hello world'.translate(transtab) #根据转换表转换字符串

'he@@* w*r@d'

translate 根据转换表转换字符串

 

partition/rpartition 返回分隔符前,分隔符,分隔符后组成的元组

partition 返回由分隔符前,分隔符,分隔符后组成的元组

从左往右

如果没有找到分隔符,返回原字符串和两个空字符串组成的元组

语法:

>>> help(str.partition)    

Help on method_descriptor:

 

partition(...)

S.partition(sep) -> (head, sep, tail)

 

Search for the separator sep in S, and return the part before it,

the separator itself, and the part after it. If the separator is not

found, return S and two empty strings.

 

示例:

>>> s = 'www.baidu.com'

    

>>> s.partition('.')

('www', '.', 'baidu.com')

 

>>> s.partition('x')

('www.baidu.com', '', '')

rpartition 类似partition,从右往左

语法:

>>> help(str.rpartition)

    

Help on method_descriptor:

 

rpartition(...)

S.rpartition(sep) -> (head, sep, tail)

 

Search for the separator sep in S, starting at the end of S, and return

the part before it, the separator itself, and the part after it. If the

separator is not found, return two empty strings and S.

 

示例:

>>> s = 'www.baidu.com'

    

>>> s.rpartition('.')

('www.baidu', '.', 'com')

 

>>> s.rpartition('x')

('', '', 'www.baidu.com')

 

replace 替换字符串

replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数count,则替换不超过count次。

 

语法:

>>> help(str.replace)

    

Help on method_descriptor:

 

replace(...)

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.

 

示例:

 

>>> s = 'hello world'

>>> s.replace('l','*')

'he**o wor*d'

 

>>> s = 'hello world\r\r\n'

>>> s

'hello world\r\r\n'

>>> s.replace('\r\r','')

'hello world\n'

strip/lstrip/rstrip去掉字符串首尾的空白字符

str.strip去掉字符串头和尾的空白字符

语法:

>>> help(str.strip)

                            

Help on method_descriptor:

strip(...)

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.

 

示例:

>>> s = '\r\n hello world\r\n '

>>> s.strip()

'hello world'

str.lstrip 去掉字符串头的空白字符

语法:

>>> help(str.lstrip)

                            

Help on method_descriptor:

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 = '\r\n hello world\r\n '

>>> s.lstrip()

'hello world\r\n '

str.rstrip去掉字符串尾的空白字符

语法:

>>> help(str.rstrip)

                            

Help on method_descriptor:

 

rstrip(...)

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.

 

示例:

>>> s = '\r\n hello world\r\n '

>>> s.rstrip()

'\r\n hello world'

split/rsplit/splitline 将字符串分隔为列表

split 按照给定的分隔符将字符串分隔为列表(从左往右)

>>> help(str.split)

                            

Help on method_descriptor:

 

split(...)

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.

如果未指定sep,即使用默认的sep=None,会把任意的空白字符当作分隔符

空白字符包括 空格,\t,\r,\n,\r\n,即空字符串会从结果列表中删除掉

从左往右分隔

 

示例1:以空白字符为分隔符,默认

示例2:指定分隔符

 

>>> s = 'www.baidu.com'                    

>>> s.split('.')                

['www', 'baidu', 'com']

 

示例3:分隔符前或后没有字符,会在结果列表中产生一个空字符

>>> s = 'www.baidu.com.'                    

>>> s.split('.')                

['www', 'baidu', 'com', '']

 

>>> s = '.www.baidu.com'                    

>>> s.split('.')                    

['', 'www', 'baidu', 'com']

 

示例:4:指定分隔次数

>>> s = 'www.baidu.com'

    

>>> s.split('.',1)

    

['www', 'baidu.com']

rsplit 按照给定的分隔符将字符串分隔为列表(从右往左)

类似split,但是从右往左分隔

 

语法:

>> help(str.rsplit)

    

Help on method_descriptor:

 

rsplit(...)

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.

 

示例:

>>> s = 'www.baidu.com'

    

>>> s.split('.',1)     #从左往右分隔1次

    

['www', 'baidu.com']

>>> s.rsplit('.',1)     #从右往左分隔1次

    

['www.baidu', 'com']

 

splitlines 按照换行符将字符串分隔为列表

>>> help(str.splitlines)

                            

Help on method_descriptor:

 

splitlines(...)

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.

 

返回S中的行列表,在行边界处中断。

结果列表中不包括换行符,除非keepends设置为True

换行符包括\r ,\n ,\r\n,不包括\r\r,\r\r\n

 

示例1:换行符包括\r ,\n ,\r\n,不包括\r\r,\r\r\n

    >>> s = 'a\tb\rc\nd\r\re\r\r\nf g'

    >>> s.splitlines()

                            

['a\tb', 'c', 'd', '', 'e', '', 'f g']

>>> s.splitlines(keepends=True)

                            

['a\tb\r', 'c\n', 'd\r', '\r', 'e\r', '\r\n', 'f g']

 

示例2:splitlines()和split('\n')的区别

 

>>> s = 'fan1 status ok\nfan2 status ok\n'

                            

>>> s.splitlines()

                            

['fan1 status ok', 'fan2 status ok']

>>> s.split('\n')

                            

['fan1 status ok', 'fan2 status ok', '']

这里末尾的\n会分隔出一个空字符串出来

 

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

>>> help(str.startswith)

    

Help on method_descriptor:

 

startswith(...)

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.

>>> '#this is a comment'.startswith('#')

True

>>> '#this is a comment'.startswith(('#','*'))

True

字符串格式化打印

format

按位置格式化

>>> "{} {}".format("hello", "world")

'hello world'

>>> "{0} {1}".format("hello", "world")

'hello world'

>>> "{1} {0} {1}".format("hello", "world")

'world hello world'

 

按变量名格式化

>>> 'my name is {name},{age} years old'.format(name = 'bob',age = 18)

'my name is bob,18 years old'

 

>> D = {'name':'hh','age':18}

>>> 'my name is {name},{age} years old'.format(**D) #通过字典提供参数

'my name is hh,18 years old'

 

>>> 'my name is {0[0]},{0[1]} years old'.format(L) #通过列表提供参数

'my name is hh,18 years old'

 

传入对象

>>> class student(object):

    def __init__(self,name,age):

        self.name=name

        self.age=age

 

        

>>> stu1 = student('bob',18)

>>> stu1.name

'bob'

>>> stu1.age

18

>>> 'my name is {0.name},{0.age} years old'.format(stu1)

'my name is bob,18 years old'

 

使用大括号转义大括号

>>> 'my name is {name},{{age}} years old'.format_map({'name':'bob','age':18})

'my name is bob,{age} years old'

>>> 'my name is {name},{{{age}}} years old'.format_map({'name':'bob','age':18})

'my name is bob,{18} years old'

 

格式化的参数

^, <, > 分别是居中、左对齐、右对齐,后面带宽度,

: 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

 

+ 表示在正数前显示 +,负数前显示 -;

(空格)表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

 

 

对齐方式

  • 居中对齐

居中对齐,指定宽度10,不指定填充字符,默认空格

>>> '{:^10}'.format('abcd')

' abcd '

居中对齐,指定宽度10,指定填充字符为*

>>> '{:*^10}'.format('abcd')

'***abcd***'

  • 左对齐

>>> '{:*<10}'.format('abcd')

'abcd******'

  • 右对齐

>>> 'my name is {name:*>10},{age} years old'.format(name = 'bob',age = 18)

'my name is *******bob,18 years old'

 

有关数字

浮点数,保留小数点后x位, .xf

>>> '{:.3f}'.format(1.1)

'1.100'

>>> '{:.3f}'.format(-1.1)

'-1.100'

>>> '{:+.3f}'.format(1.1)

'+1.100'

>>> '{:+.3f}'.format(-1.1)

'-1.100'

不带小数,四舍五入

>>> '{:.0f}'.format(1.1)

'1'

>>> '{:.0f}'.format(1.6)

'2'    

 

整数

>>> '{:0>5d}'.format(5) #右对齐,宽度5,补位0

'00005'

>>> '{:x>5d}'.format(5)    #右对齐,宽度5,补位x

'xxxx5'

>>> '{:0<5d}'.format(5)

'50000'

>>> '{:x<5d}'.format(5)

'5xxxx'

>>> '{:,}'.format(5) #以逗号分隔,不能再指定宽度了

'5'

>>> '{:,}'.format(50000)

'50,000'

>>> '{:x>10}'.format('{:,}'.format(50000)) #可以嵌套

'xxxx50,000'

 

百分数

>>> '{:.2%}'.format(0.2)

'20.00%'

 

%操作符

%[(name)][flags][width].[precision]typecode

 

  • (name) 为命名
  • flags 可以有 +,-,' '或 0。

    + 表示右对齐。

    - 表示左对齐。

    ' ' 为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。

    0 表示使用 0 填充。

  • width 表示显示宽度
  • precision 表示小数点后精度
  • 类型码:

    %s 字符串 (采用str()的显示)

    %r 字符串 (采用repr()的显示)

    %c 单个字符

    %b 二进制整数

    %d 十进制整数

    %i 十进制整数

    %o 八进制整数

    %x 十六进制整数

    %e 指数 (基底写为e)

    %E 指数 (基底写为E)

    %f 浮点数

    %F 浮点数,与上相同%g 指数(e)或浮点数 (根据显示长度)

    %G 指数(E)或浮点数 (根据显示长度)

    %% 字符"%"

 

>>> '%+10s'%('bob') #右对齐,宽度10

' bob'

>>> '%-10s'%('bob') #左对齐,宽度10

'bob '

posted @ 2020-10-01 00:46  jeancheng  阅读(246)  评论(0编辑  收藏  举报