python string

[b]如果这就是字符串,这本来就是字符串[/b]

首先看下字符串的方法

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']



lower(...)
Return a copy of the string s converted to lowercase.
将字符串中大写字母转换为小写

upper(...)
Return a copy of the string s converted to uppercase.
将字符串中小写字母转换为大写

swapcase(...)
Return a copy of the string s with upper case characters
converted to lowercase and vice versa.
将字符串中的字母互换大小写

strip(...)
S.strip([chars]) -> string or unicode

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.
If chars is unicode, S will be converted to unicode before stripping
移出字符串首尾的空格
lstrip(...)
S.lstrip([chars]) -> string or unicode

Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
移出字符串首部的空格
rstrip(...)
S.rstrip([chars]) -> string or unicode

Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
移出字符串尾部的空格

split(...)
S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string 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.
分割字符串,如果给定了分隔符,按照分隔符号分割,否则按照空格进行分割。
如果指定了最大分割次数,则按照最大分割次数分割,否则分割所有。

rsplit(...)
S.rsplit([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string 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 or is None, any whitespace string
is a separator.
同split作用一样,但是是从尾部开始进行分割。

join(...)
S.join(iterable) -> string

Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
方法中传递的参数是一个iterable,然后在元素之间加入分隔符串联成一个字符串返回。

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.
判断一个字符串的开始

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.
判断一个字符串的结尾

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.
计算指定子字符串sub的出现次数

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.
找到指定子字符串sub首次出现的位置,否则返回-1

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.
找到一个子字符串最后一次出现的位置

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

Like S.find() but raise ValueError when the substring is not found.
找到指定子字符串sub首次出现的位置,否则报错。

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

Like S.rfind() but raise ValueError when the substring is not found.
找到指定子字符串sub最后一次出现的位置,否则报错。

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

Return S left-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
>>> s='abcde'
>>> s.ljust(10)
'abcde '

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

Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space)
在长度为width的字符串内向右对齐。
>>> s='abcde'
>>> s.rjust(10)
' abcde'

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.
使用分隔符字符串sep划分字符串,返回一个元组。
>>> s='abcde'
>>> s.partition('c')
('ab', 'c', 'de')

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.
使用分隔符字符串sep划分字符串,但是从字符串的结尾处开始搜索。

encode(...)
S.encode([encoding[,errors]]) -> object

Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. 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 is able to handle UnicodeEncodeErrors.
返回字符串的编码版本

decode(...)
S.decode([encoding[,errors]]) -> object

Decodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that is
able to handle UnicodeDecodeErrors.
解码一个字符串并返回一个Unicode字符串,

capitalize(...)
S.capitalize() -> string

Return a copy of the string S with only its first character
capitalized.center
首字符变成大写
center(...)
S.center(width[, fillchar]) -> string

Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
在长度为width的字段内将字符串居中。pad是填充字符。
expandtabs(...)
S.expandtabs([tabsize]) -> string

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.
使用空格替换制表符

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

Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
格式化

replace(...)
S.replace(old, new[, count]) -> string

Return a copy of string 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 [,deletechars]) -> string

Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256.
使用一个字符转换表table转换字符串,删除deletechars中的字符

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.
将字符串分为一个行列表,如果keepends为1,则保留各行最后的换行符。

title(...)
S.title() -> string

Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.
将字符串转换为标题格式
s='hello,word'
s.title()
输出:'Hello,World'

zfill(...)
S.zfill(width) -> string

Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
在字符串的左边填充0,直至其宽度为width

isalnum
检查所有字符是否都为字母或数字
isalpha
检查所有字符是否都为字母
isdigit
检查所有字符是否都为数字
islower
检查所有字符是否都为小写
isspace
检查所有字符是否都为空白
istitle
检查所有字符是否为标题字符串
isupper
检查所有字符是否为大写


Q:

1、给定字符串 s='simple is better' 统计字符串中字符出现的次数,并且按照次数排序。

def f_1(s):
counter = {}
for i in s:
if not counter.has_key(i):
counter[i] = s.count(i)
else:
continue
return sorted(counter.items(), key=lambda d: d[1],reverse=True)


2、给定一个list,转换为字符串。list=['d','o','n','e']转换为字符串'done'.

def f(l):
return ''.join(l)


参考资料:
http://docs.python.org/2/library/string.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值