python 中的 用chr()数值转化为字符串,字符转化为数值ord(s)函数

1.1 python字符串定义

  1.  
    #!/usr/bin/python
  2.  
    # -*- coding: utf8 -*-
  3.  
     
  4.  
    # 定义一个字符串
  5.  
    s1 = 'this is long String that spans two lines'
  6.  
     
  7.  
    # 表示下面一行是上一行的延续
  8.  
    s2 = 'this is long String\
  9.  
    that spans two lines'
  10.  
     
  11.  
    #原样输出字符串
  12.  
    s3 = """this is long String
  13.  
    that spans two lines
  14.  
    """
  15.  
    # 换行输出字符串
  16.  
    s4 = 'this is long String\n\
  17.  
    that spans two lines'
  18.  
     
  19.  
    print "s1=",s1
  20.  
    print "s2=",s2
  21.  
    print "s3=",s3
  22.  
    print "s4=",s4

输出结果:

  

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

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

  1.  
    #!/usr/bin/python
  2.  
    # -*- coding: utf8 -*-
  3.  
    # 字符转化为数值
  4.  
    s = 'a'
  5.  
    print ord( s)
  6.  
    # 数值转化为字符串
  7.  
    b = 97
  8.  
    print chr(b)

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

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

  1.  
    #!/usr/bin/python
  2.  
    # -*- coding: utf8 -*-
  3.  
     
  4.  
    #把unicode码值转化为字符串
  5.  
    print repr(unichr( 8224))
  6.  
    #把unicode字符串转化为码值
  7.  
    print repr(ord( u'\u2020'))

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

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

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

猜你喜欢

转载自www.cnblogs.com/presleyren/p/11365816.html
今日推荐