标签:odi count lines window 制表符 print sys code ==
Python3 字符串类型:>> s = "abc"
>> type(s)
<class ‘str‘>
Bytes 字节字符串
>> s1 = b"abc"
>> type(s1)
<class ‘bytes‘>>> b = "中国".encode("gbk")
>> b
b‘\xd6\xd0\xb9\xfa‘
>> type(b)
<class ‘bytes‘>
不是在内存中保存的时候都用bytes
ord chr 处理中文
>> s = "中"
>> ord(s)
20013
>> chr(21450)
‘及‘
>> chr(21458)
‘叒‘
sys.getdefaultencoding() 获取默认编码
>> s = "中国"
>> import sys
>> sys.getdefaultencoding()
‘utf-8‘
换行和转义
\ 换行符
\ 反斜杠
\’ 单引号
\” 双引号
\n 换行
\t 横向制表符
\v 纵向制表符
\r 回车
\f 换页
Windows 默认的换行是 \n \r
>> os.linesep
‘\r\n‘
Linux 默认换行是\n
>> print("‘")
‘>> print(‘1\n2\n3‘)
1
2
3
>> print(‘\‘‘)
‘>> print("\"")
"
相同字符串的内存地址是相同的
>> a
‘ab‘
>> id(a)
36280640L
>> id("ab")
36280640L
格式化字符串
>> "abc{}".format("x")
‘abcx‘
>> "abc{}{}".format("x","u")
‘abcxu‘>> "abc{1}{0}".format("x","y")
‘abcyx‘>> "%s = %s " %(1,2)
‘1 = 2 ‘>> "%d = %d " %(1,2)
‘1 = 2 ‘>> "%.2f =%.2f" %(1.999,2.5555)
‘2.00 =2.56‘
Template
from string import Template
s = Template(‘There are ${key1} ${key2} Quotations Symbols‘)
print (s.substitute(key2=‘Python‘, key1=3))
字符串关系判断
>> "a" in "abc"
True
>> "a" not in "abc"
False
>>
>> "a" != "a"
False>> "a" is "a"
True
习题3:统计首字母是“a”的单词的个数
s = "akk alklk bkk aaddd"
count =0
for v in s.split():
if v[0] =="a":
count += 1
print(count)
习题4:单词顺序翻转
>> " ".join(s.split()[::-1])
‘boy a am i‘
习题5:单词顺序翻转且单词本身翻转
s = "i am a boy"
print(" ".join([word[::-1] for word in s.split()[::-1]]))
print(s[::-1])
strip()
去除字符串两端的空白,可以去除\r \n \t \f 和空白字符
可指定去除的字符,从开头和结尾搜索需要去除的字符串
>> s = " \r\n\tabc\n "
>> s.strip()
‘abc‘
>> s = "abc"
>> s.strip("*")
‘abc‘>> s = "!!!abc!!!"
>> s.strip("!")
‘abc!!!‘
>> s = "!!!abc!!!"
>> s.strip("!")
‘abc‘
>> s = "!!!abc!!!"
>> s.strip("!*")
‘abc‘
rstrip()
去除字符串右端的空白
>> s = "!!!abc!!!"
>> s.rstrip("!*")
‘!!!***abc‘
lstrip()
去除字符串左边的空白
>> " \t\r\n abc".lstrip()
‘abc‘
标签:odi count lines window 制表符 print sys code ==
原文地址:http://blog.51cto.com/13496943/2306586