__builtins__.str class

__builtins__.str class 

和String输出位置相关函数

# capitalize(...)
#     S.capitalize() -> str
#     
#     Return a capitalized version of S, i.e. make the first character
#     have upper case and the rest lower case.

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

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

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

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

a = 'Life is Short, Lets Pythoning'
a1 = a.capitalize()
print(a1)
a2 = a.center(50,"*")
print(a2)
a3 = a.center(50)
print(a3)
a4 = a.ljust(50,"*")
print(a4)
a5 = a.rjust(50,"*")
print(a5)
a6 = a.zfill(50)
print(a6)
# Life is short, lets pythoning
# **********Life is Short, Lets Pythoning***********
# Life is Short, Lets Pythoning
# Life is Short, Lets Pythoning*********************
# *********************Life is Short, Lets Pythoning
# 000000000000000000000Life is Short, Lets Pythoning
# 注:文件中的换行符号:
# linux/unix: \r\n
# windows   : \n 
# Mac OS    : \r 
# \t表示键盘上的TAB建

count

# 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.
# str.count(str,[beg,len])    返回子字符串在原字符串出现次数,beg,len是范围,从左0开始,包含左边的数,不包含右边的数,类似 0 <= len < max
a = 'Life is Short, Lets Pythoning'
b1 = a.count("i", 1)
print(b1) 
encode

# 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.
a = 'string'
print(a.encode(encoding = 'gb2312')) # b'string'
endswith & startswith

endswith
# 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.
<strong>startswith</strong>
# 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.
a = 'string'
print(a.startswith('st'))  # True
print(a.endswith('ng'))    # True
str. expandtabs(tabsize = 8)     把字符串的tab转为空格,默认为8个  

find

# 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.
a = 'string'
print(a.find('r')) # 2
index

# index(...)
#     S.index(sub[, start[, end]]) -> int
#     
#     Like S.find() but raise ValueError when the substring is not found.
a = 'string'
print(a.index('r')) # 2
print(a.index('a')) # ValueError: substring not found

join

# join(...)
#     S.join(iterable) -> str
#     
#     Return a string which is the concatenation of the strings in the
#     iterable.  The separator between elements is S.
e.g.1
print('|'.join(('a','b','c')))
print('|'.join({'a':1, 'b':2, 'c':3}))
# a|b|c
# a|b|c

e.g.2
from collections import Counter
c = Counter('abcdeabcdabcaba')
print(''.join(sorted(c.elements())))
# aaaaabbbbcccdde
split

# 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.
# str.split(sep)       以str作为分隔符,将一个字符串分隔成一个序列,num是被分隔的字符串 
b1 = "Life,is,Short,Lets,Pythoning"
b2 = ","
b3 = b1.split(sep = b2)
print(b3) 
splitlines

# 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.
a = 'ab c\n\nde fg\rkl\r\n'.splitlines()
print(a)
b = 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends = True)
print(b)
print("==============")
a = '-'.join('ab c\n\nde fg\rkl\r\n'.splitlines())
print(a)
b = '-'.join('ab c\n\nde fg\rkl\r\n'.splitlines(keepends = True))
print(b)
# ['ab c', '', 'de fg', 'kl']
# ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
# ==============
# ab c--de fg-kl
# ab c
# -
# -de fg
# -kl
partition

# 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.
a = "WELLCOME TO PYTHON'S WORLD!"
a1 = a.lower()
print(a1)
a2 = a1.partition("python")
print(a2) 
# wellcome to python's world!
# ('wellcome to ', 'python', "'s world!")
replace & translate & maketrans

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

# translate(...)
#     S.translate(table) -> str
#     
#     Return a copy of the string S, where all characters have been mapped
#     through the given translation table, which must be a mapping of
#     Unicode ordinals to Unicode ordinals, strings, or None.
#     Unmapped characters are left untouched. Characters mapped to None
#     are deleted.
#相当于replace的加强版

# 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.
map = str.maketrans('123', 'abc') #maketrans建立映射,供translate使用
print(map)               # {49: 97, 50: 98, 51: 99}
s = '54321123789' 
a = s.translate(map)
print(a)                 # 54cbaabc789

其他

str.isalnum()               检查字符串是否以字母和数字组成,是返回true否则False  
str.isalpha()               检查字符串是否以纯字母组成,是返回true,否则false  
str.isdecimal()             检查字符串是否以纯十进制数字组成,返回布尔值  
str.isdigit()               检查字符串是否以纯数字组成,返回布尔值  
str.islower()               检查字符串是否全是小写,返回布尔值  
str.isupper()               检查字符串是否全是大写,返回布尔值  
str.isnumeric()             检查字符串是否只包含数字字符,返回布尔值  
str.isspace()               如果str中只包含空格,则返回true,否则FALSE  
str.title()                 返回标题化的字符串(所有单词首字母大写,其余小写)  
str.istitle()               如果字符串是标题化的(参见title())则返回true,否则false  
str.lower()                 将大写转为小写  
str.upper()                 转换字符串的小写为大写  
str.swapcase()              翻换字符串的大小写  
str.lstrip()                去掉字符左边的空格和回车换行符  
str.rstrip()                去掉字符右边的空格和回车换行符  
str.strip()                 去掉字符两边的空格和回车换行符  









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值