Python 学习笔记 字符串
2015-08-04 14:39
696 查看
在2.7中 如果使用中文 需要在最开始使用#coding=utf-8才能够运行
#已知字符串 s = "i,am,lilei",请用两种办法取出之间的“am”字符。
可以通过在其他对象中添加list或者dict来变相解决例如tuple等不能变的问题
字符串拼接:
常用 字符串工具可以在字符串的方法中找 例如replace(替换),isupper(是否大写),islower(是否小写),swapcase(大小写转换),len(长度)等等
sort()是对传入的元素进行排序
sorted(0是返回排序之后的元素
需要插入\ 之类的特殊符号时候 需要在前面加一个\
下面是一些字符串相关的练习题
#已知字符串 s = "i,am,lilei",请用两种办法取出之间的“am”字符。
import string s = "i,am,lilei" s1=s.split(',')#分割结果是list print s[2:4] print s1[1] print s[1,1,2]#开始 结束 步进(集合也适用)
可以通过在其他对象中添加list或者dict来变相解决例如tuple等不能变的问题
字符串拼接:
print "%s%s" % ('a','b') print "{a} {b}".format(a='a',b='b')#字符串较多时 建议用这种(使用format是无序的) print a,b print a+b
常用 字符串工具可以在字符串的方法中找 例如replace(替换),isupper(是否大写),islower(是否小写),swapcase(大小写转换),len(长度)等等
sort()是对传入的元素进行排序
sorted(0是返回排序之后的元素
需要插入\ 之类的特殊符号时候 需要在前面加一个\
print \\ #\ print \n #换行符
下面是一些字符串相关的练习题
#定义一个方法func,该func可以引入任意多的字符串参数, #结果返回(长度)最长的字符串 def func2(*input_str): longest_str='' for x in input_str: if isinstance(x, str): if len(x) > len(longest_str): longest_str=x else: print x,'is not str type value' return longest_str print func2('asdasd','zxczxc','12343rfdgrdqweqwe','123')
#统计该文档中,"be" "is" "than" 的出现次数 str1='''The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!''' str2=str1.split(' ')#返回list 然后对list 遍历 num1=0 num2=0 num3=0 for x in str2: temp=x.strip() if temp == 'be': num1=num1+1 elif temp == 'is': nm2=num2+1 elif temp == 'than': num3=num3+1 print num1,num2,num3
相关文章推荐
- Python中逐行读取文件内容的办法
- python练习题(三)
- python的一些总结4
- python的一些总结3
- Python Requests快速入门
- python的一些总结2
- python遇到‘\u’开头的unicode编码
- python的一些总结1
- Python中return语句用法实例分析
- pickle和cPickle——python对象序列化
- python函数形参用法实例分析
- Python简明入门教程
- 将Python代码打包为jar软件的简单方法
- python函数局部变量用法实例分析
- pyhton_学习笔记0804
- python 安装easy_install和pip
- Python中通过函数对象创建全局变量
- python删除列表内容
- 从零开始学Python
- 从零开始学Python