Python 学习 字符串

在2.7中 如果使用中文 需要在最开始使用#coding=utf-8才能够运行

#已知字符串 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   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(' ')
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值