一句python,一句R︱python中的字符串操作、中文乱码、NaN情况
先学了R,最近刚刚上手Python,所以想着将python和R结合起来互相对比来更好理解python。最好就是一句python,对应写一句R。
pandas可谓如雷贯耳,数据处理神器。
以下符号:
=R=
代表着在R中代码是怎么样的。
————————————————————————————————————————————
字符编码
encode 和 decode
Python2 默认的编码是 ascii,通过 encode 可以将对象的编码转换为指定编码格式(称作“编码”),而 decode 是这个过程的逆过程(称作“解码”)。
decode,将字节串转变为字符串,并且这个字符串是按照 unicode 编码的。在 unicode 编码中,一个汉字对应一个字符,这时候度量它的长度就是 1.
encode,一个 unicode 编码的字符串,也可以转换为字节串。
[html] view plain copy
print?
>>> a = "中"
>>> a
'\xe4\xb8\xad'
>>> b = a.decode()
>>> b
u'\u4e2d'
其中,a就是ASCII格式的编码,字节串;b就是unicode编码的字符串。当然有一个问题就是最后出来的还不是汉字。。。(醉!)
————————————————————————————————————————————
一、字符形成、展示、拼接、切片
1、字符形成=R=paste
双引号包裹单引号
[html] view plain copy
print?
>>> "What's your name?"
"What's your name?"
单引号使用转义符
[html] view plain copy
print?
>>> 'What\'s your name?'
"What's your name?"
2、字符串展示print /raw_input
[html] view plain copy
print?
>>> name = raw_input("input your name:")
input your name:python
>>> name
'python'
其中raw_input有点交互关系,具体看案例,直接键入name就可以获得你输入的内容。
[html] view plain copy
print?
>>> print("hello, world")
hello, world
3、字符切片、选择、截取 =R=无
字符可以像一般的数据格式一样进行切片选择,有点像series:
[html] view plain copy
print?
>>> lang = "study Python"
>>> lang[0]
's'
>>> lang[2:9]
'udy pyt'
当然也包括lang[:]可以选中所有的。
其中index代表着某个字符的索引值。
[html] view plain copy
print?
lang.index("p")
4、内存编号 =R= 无
这个与R中不一样,当数据存入python之后,机器会自动给存入内存的数据编号,这个编号可以用id来查看。
[html] view plain copy
print?
>>> id(c)
3071934536L
>>> id(lang)
3071934536L
5、ASCII 值(是十进制的)
ord("a") 代表输入字符返回ASCII值
cha(97) 代表输入ASCII值返回字符
[html] view plain copy
print?
>>> cmp("a","b") #a-->97, b-->98, 97 小于 98,所以 a 小于 b
-1
其中cmp()代表比较 a b 两个字符的ASCII值的大小,返回值为1,0,-1
[html] view plain copy
print?
>>> max(str1)
'd'
>>> max(str2)
'e'
>>> min(str1)
'a'
返回字符的ASCII值的最大值。
————————————————————————————————————————————
二、字符串基本操作
1、字符串重复 =R=rep
[html] view plain copy
print?
>>> str1*3
'abcdabcdabcd'
其中变成字符串有两种方式:一种是str()或者是用单引号来表示。
2、字符串拼接
(1) 号 =R= paste
[html] view plain copy
print?
>>> "Py" "thon"
'Python'
>>> a = 1989
>>> b = "free"
>>> print b “a”
>>> print b str(a)
其中变成字符串有两种方式:一种是str()或者是用单引号来表示。
乘法,就是重复那个字符串的含义。
(2)join =R= paste
用 . 来填补间隔中的内容。
3、语句分割split =R= split
这个函数的作用是将字符串根据某个分割符进行分割。
[html] view plain copy
print?
>>> a = "I LOVE PYTHON"
>>> a.split(" ")
['I', 'LOVE', 'PYTHON']
其中split(“ ”)括号中,代表着依据什么样式来进行分割。
4、字符串去掉空格 = R=grep
方法是:
S.strip() 去掉字符串的左右空格
S.lstrip() 去掉字符串的左边空格
S.rstrip() 去掉字符串的右边空格
[html] view plain copy
print?
>>> b=" hello " # 两边有空格
>>> b.strip()
'hello'
5、字符串大小写
在 Python 中有下面一堆内建函数,用来实现各种类型的大小写转化
S.upper() #S 中的字母大写
S.lower() #S 中的字母小写
S.capitalize() # 首字母大写
S.isupper() #S 中的字母是否全是大写
S.islower() #S 中的字母是否全是小写
S.istitle()