- 浏览: 248092 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (127)
- vim (3)
- python (44)
- pymysql (1)
- mysql (9)
- macvim (1)
- erlang (3)
- twisted (0)
- tornado (5)
- django (7)
- postgresql (5)
- sql (1)
- java (7)
- tech (4)
- cache (1)
- lifestyle (3)
- html (1)
- ubuntu (2)
- rabbitmq (1)
- algorithm (8)
- Linux (4)
- Pythonista (1)
- thread (1)
- sort (6)
- 设计模式 (1)
- search (1)
- Unix (6)
- Socket (3)
- C (2)
- web (1)
- gc (1)
- php (10)
- macos (1)
最新评论
-
2057:
这个程序有bug。
查找算法学习之二分查找(Python版本)——BinarySearch -
dotjar:
NB
一个Python程序员的进化[转]
如果这就是字符串,这本来就是字符串
首先看下字符串的方法
Q:
1、给定字符串 s='simple is better' 统计字符串中字符出现的次数,并且按照次数排序。
2、给定一个list,转换为字符串。list=['d','o','n','e']转换为字符串'done'.
参考资料:
http://docs.python.org/2/library/string.html
首先看下字符串的方法
>>> 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
发表评论
-
macos 10.9.2 clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command
2014-03-25 19:13 1769方法总是有的,当然需要你去寻找。 当然如果花费太多的时间在一件 ... -
PostgreSQL psycopg2:IndexError: tuple index out of range
2014-01-09 17:04 2234Postgresql psycopg2使用like查询的时候 ... -
Python 迭代器和生成器
2013-10-15 23:09 2854迭代器 迭代器只不过是一个实现迭代器协议的容器对象。它基于两个 ... -
Python时间模块
2013-10-15 23:03 3478time模块 时间模块中最常用的一个函数就是获取当前时间的函数 ... -
Python装饰器
2013-10-15 22:59 1572编写自定义装饰器有许多方法,但最简单和最容易理解的方法是编写一 ... -
python list
2013-10-15 22:56 1260简单总结以及整理如下: >>> dir( ... -
Python Excel
2013-09-10 17:21 979安装lib easy_install xlrd def ... -
排序算法学习(python版本)之堆排序(HeapSort)
2013-07-01 22:54 2004Contains: 堆排序以及堆排序的应用 堆排序(Heaps ... -
python range xrange
2013-06-25 23:30 1158引用Help on built-in function ran ... -
python class
2013-06-25 00:54 1832引用类是创建新对象类 ... -
AttributeError: 'module' object has no attribute 'SendCloud'
2013-06-05 11:46 7093网上查了下 意思是说你命名的文件名不能和lib重名,这样会导 ... -
Python property
2013-03-29 19:56 0由于之前有总结过,可以参考http://2057.iteye. ... -
python tips
2013-03-28 23:57 8891、enum #!/usr/bin/env python ... -
python decorators
2013-03-28 23:36 1371Contains: 1、decorators 2、funct ... -
python closures
2013-03-28 22:09 1195Closure:如果在一个内部函数里,对在外部作用域(但不是在 ... -
Python map、filter,reduce介绍
2013-03-28 22:02 13191、filter(function,iterable) 引用C ... -
Python __new__ 、__init__、 __call__
2013-03-26 23:49 5359Contains: __new__: 创建对象时调用,返回当 ... -
Python socket简介
2013-03-25 23:42 2181自豪地使用dir和help. Python 2.7.2 ( ... -
Tornado ioloop源码简析
2013-03-21 00:18 2856#!/usr/bin/env python #-*-en ... -
Tornado httpserver 源码简析
2013-03-17 01:49 1793整个流程就是创建一个socket socket.socket ...
相关推荐
Python string类型,字符串转化成整数,转化成浮点数,了解常见的转义字符,什么是切片?如何使用切片截取字符串,做好小练习
然而,如果希望`\`本身被当作普通字符输出,可以使用`r`前缀创建原始字符串(raw string): ```python d = r"gao zhen ni hao \ ni hao ma" ``` 在`d`中,`\`将被视为普通字符,不会引起转义。 ### 字符串连接与...
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) #...
一、python3对文本和二进制数据做了区分。文本是Unicode编码,str类型,用于显示。二进制类型是bytes类型,用于存储和传输。bytes是byte的序列,而str是unicode的序列。 str类型: >>> s = u'你好' >>> s '你好'...
在Python编程语言中,字符...在实际项目中,`string_clean.py`可能包含实现这些功能的函数,以便对输入字符串进行完整的处理流程。通过结合以上方法,我们可以创建一个强大的字符串清理工具,适用于各种文本处理场景。
在Python编程语言中,逆序输出字符串是一项基本且常见的操作,尤其在处理文本数据时非常有用。例如,我们可能需要反转用户输入、处理文本文件,或者进行字符串的其他操作。这个压缩包文件“Python代码源码-实操案例-...
new_string = string.replace("World", "Python") print(new_string) # 输出:"Hello, Python!" ``` 5. **split() 函数** split() 函数根据指定的分隔符将字符串分割成多个子串,并返回一个包含这些子串的列表...
本文实例讲述了python实现string和dict的相互转换方法。分享给大家供大家参考,具体如下: 字典(dict)转为字符串(string) 我们可以比较容易的将字典(dict)类型转为字符串(string)类型。 通过遍历dict中的所有元素就...
python字符串转义字符python字符串转移字符python字符串转义字符python字符串转义字符python字符串转义字符
Python中的`replace()`函数是字符串操作的一个重要工具,它允许你在字符串中查找并替换特定的子串。这个函数对于处理文本数据,尤其是处理用户输入或从文件读取的数据时非常有用。下面我们将深入探讨`replace()`函数...
### Python格式化输出:f-string格式化输出 在Python中,字符串格式化是处理和展示数据的一种重要方式。从早期的`%s`格式化到`str.format()`方法,再到Python 3.6中引入的f-string(格式化字符串字面量),Python中...
实例如下: # bytes object b = bexample # str object s = example ...以上这篇python字符串str和字节数组相互转化方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多
本篇内容介绍了如何使用Python编写一个简单的脚本程序,将字符串转换成十六进制(Hex)表示形式,并将结果写入到文件中。以下是详细的知识点说明: ### Python字符串转换为十六进制 #### 实现目标 主要目标是编写...
根据提供的标题、描述、标签以及部分内容,我们可以详细探讨这20个Python编程技巧中的几个示例,以此为基础进一步深入理解这些技巧如何提升编程效率及代码的可读性。 ### 1. 字符串反转 使用Python切片进行字符串...
这个名为"Algorithm-python-string-similarity.zip"的压缩包包含了一个Python库,用于计算不同字符串之间的相似度和距离。在这个库中,我们可以找到多种经典的字符串相似性算法的实现。 首先,我们要理解什么是字符...
### 一、Python字符串处理基础 在Python中,字符串是一种常见的数据类型,用于存储文本信息。在本例中,我们使用了一个包含英文单词的字符串 `string` 来进行操作。 **代码示例**: ```python string = '''...
Python 如何转换string到float?简单几步,让你轻松解决。 打开软件,新建python项目,如图所示 右键菜单中创建.py文件,如图所示 步骤中文件输入代码如下: def string_to_float(str): return float(str) if __...
### Python字符串处理技巧详解 #### 一、Python中的清屏指令 在Python中,可以通过调用`os`模块中的`system`方法来实现控制台的清屏操作。 ```python import os os.system('cls') # 在Windows操作系统中 ``` 此命令...
在Python编程中,处理表格数据是一项常见的任务,尤其是在数据分析、数据清洗或报告生成等领域。本教程将详细讲解如何使用Python将表格单行数据拼接成一个字符串。首先,我们需要了解两个关键库:Pandas和String操作...
该库基本上包含在python包string_utils ,其中包含以下模块: validation.py (包含字符串检查API) manipulation.py (包含字符串转换api) generation.py (包含字符串生成api) errors.py (包含特定于库的...