1.1 python字符串定义

#!/usr/bin/python
# -*- coding: utf8 -*-

# 定义一个字符串
s1 = 'this is long String that spans two lines'

# 表示下面一行是上一行的延续
s2 = 'this is long String\
that spans two lines'

#原样输出字符串 
s3 = """this is long String 
     that spans two lines
     """
# 换行输出字符串
s4 = 'this is long String\n\
     that spans two lines'

print "s1=",s1 
print "s2=",s2
print "s3=",s3
print "s4=",s4

 

输出结果:

  

1.2 python字符与字符值之间的转换

 A :字符转化为数值&数值转化为字符串:其中ord函数可以把字符串转化为整数的范围为【0,65535】

#!/usr/bin/python
# -*- coding: utf8 -*-
# 字符转化为数值
s = 'a'
print ord(s)
# 数值转化为字符串
b = 97
print chr(b)

B:chr()函数的参数args在【0,256】,意思就是只能把【0,256】的数字转化为字符串

C:把一个Unicode码值转化为一个Unicode字符串

#!/usr/bin/python
# -*- coding: utf8 -*-

#把unicode码值转化为字符串
print repr(unichr(8224))
#把unicode字符串转化为码值
print repr(ord(u'\u2020'))

 

D:chr()函数与str函数的区别:

           1. chr()函数是把一个小整数作为参数,并返回对应于ASCII单字符的字符串

           2. str()函数是把任何整数作为参数,返回一个该整数的文本形式的字符串

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐