`

python string

阅读更多
如果这就是字符串,这本来就是字符串

首先看下字符串的方法
>>> 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


分享到:
评论

相关推荐

    Python string.html

    Python string类型,字符串转化成整数,转化成浮点数,了解常见的转义字符,什么是切片?如何使用切片截取字符串,做好小练习

    Python string 操作举例,列举python操作字符传的基本操作

    然而,如果希望`\`本身被当作普通字符输出,可以使用`r`前缀创建原始字符串(raw string): ```python d = r"gao zhen ni hao \ ni hao ma" ``` 在`d`中,`\`将被视为普通字符,不会引起转义。 ### 字符串连接与...

    Python string 操作举例,字符串的初始化,在python中显得更灵活了

    python基础训练题 a = '''gao zhen ni hao''' print (a) b = "gao\nzhen\nni\nhao" print (b) c = "gao zhen ni hao \ ni hao ma" print (c) d = r"gao zhen ni hao \ ni hao ma" print (d) #at = type(a) #...

    详解python string类型 bytes类型 bytearray类型

    一、python3对文本和二进制数据做了区分。文本是Unicode编码,str类型,用于显示。二进制类型是bytes类型,用于存储和传输。bytes是byte的序列,而str是unicode的序列。 str类型: >>> s = u'你好' >>> s '你好'...

    python字符串处理去掉符号加空格

    在Python编程语言中,字符...在实际项目中,`string_clean.py`可能包含实现这些功能的函数,以便对输入字符串进行完整的处理流程。通过结合以上方法,我们可以创建一个强大的字符串清理工具,适用于各种文本处理场景。

    Python代码源码-实操案例-框架案例-使用Python逆序输出字符串.zip

    在Python编程语言中,逆序输出字符串是一项基本且常见的操作,尤其在处理文本数据时非常有用。例如,我们可能需要反转用户输入、处理文本文件,或者进行字符串的其他操作。这个压缩包文件“Python代码源码-实操案例-...

    python-文本函数(1).docx

    new_string = string.replace("World", "Python") print(new_string) # 输出:"Hello, Python!" ``` 5. **split() 函数** split() 函数根据指定的分隔符将字符串分割成多个子串,并返回一个包含这些子串的列表...

    python实现字典(dict)和字符串(string)的相互转换方法

    本文实例讲述了python实现string和dict的相互转换方法。分享给大家供大家参考,具体如下: 字典(dict)转为字符串(string) 我们可以比较容易的将字典(dict)类型转为字符串(string)类型。 通过遍历dict中的所有元素就...

    string转义字符.jpg

    python字符串转义字符python字符串转移字符python字符串转义字符python字符串转义字符python字符串转义字符

    python中的replace函数.docx

    Python中的`replace()`函数是字符串操作的一个重要工具,它允许你在字符串中查找并替换特定的子串。这个函数对于处理文本数据,尤其是处理用户输入或从文件读取的数据时非常有用。下面我们将深入探讨`replace()`函数...

    python格式化输出:fstring格式化输出.docx

    ### Python格式化输出:f-string格式化输出 在Python中,字符串格式化是处理和展示数据的一种重要方式。从早期的`%s`格式化到`str.format()`方法,再到Python 3.6中引入的f-string(格式化字符串字面量),Python中...

    python字符串str和字节数组相互转化方法

    实例如下: # bytes object b = bexample # str object s = example ...以上这篇python字符串str和字节数组相互转化方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多

    python 处理string到hex脚本的方法

    本篇内容介绍了如何使用Python编写一个简单的脚本程序,将字符串转换成十六进制(Hex)表示形式,并将结果写入到文件中。以下是详细的知识点说明: ### Python字符串转换为十六进制 #### 实现目标 主要目标是编写...

    Python你需要知道的20个常用的Python技巧

    根据提供的标题、描述、标签以及部分内容,我们可以详细探讨这20个Python编程技巧中的几个示例,以此为基础进一步深入理解这些技巧如何提升编程效率及代码的可读性。 ### 1. 字符串反转 使用Python切片进行字符串...

    Algorithm-python-string-similarity.zip

    这个名为"Algorithm-python-string-similarity.zip"的压缩包包含了一个Python库,用于计算不同字符串之间的相似度和距离。在这个库中,我们可以找到多种经典的字符串相似性算法的实现。 首先,我们要理解什么是字符...

    用python切分英文单词

    ### 一、Python字符串处理基础 在Python中,字符串是一种常见的数据类型,用于存储文本信息。在本例中,我们使用了一个包含英文单词的字符串 `string` 来进行操作。 **代码示例**: ```python string = '''...

    Python将string转换到float的实例方法

    Python 如何转换string到float?简单几步,让你轻松解决。 打开软件,新建python项目,如图所示 右键菜单中创建.py文件,如图所示 步骤中文件输入代码如下: def string_to_float(str): return float(str) if __...

    python字符串处理实例.docx

    ### Python字符串处理技巧详解 #### 一、Python中的清屏指令 在Python中,可以通过调用`os`模块中的`system`方法来实现控制台的清屏操作。 ```python import os os.system('cls') # 在Windows操作系统中 ``` 此命令...

    基于Python实现拼接表格单行数据为字符串.zip

    在Python编程中,处理表格数据是一项常见的任务,尤其是在数据分析、数据清洗或报告生成等领域。本教程将详细讲解如何使用Python将表格单行数据拼接成一个字符串。首先,我们需要了解两个关键库:Pandas和String操作...

    python-string-utils:方便的Python库,用于验证,操作和生成字符串

    该库基本上包含在python包string_utils ,其中包含以下模块: validation.py (包含字符串检查API) manipulation.py (包含字符串转换api) generation.py (包含字符串生成api) errors.py (包含特定于库的...

Global site tag (gtag.js) - Google Analytics