python 中的 用chr()數值轉化為字符串,字符轉化為數值ord(s)函數


1.1 python字符串定義

  1. #!/usr/bin/python
  2. # -*- coding: utf8 -*-
  3. # 定義一個字符串
  4. s1 = 'this is long String that spans two lines'
  5. # 表示下面一行是上一行的延續
  6. s2 = 'this is long String\
  7. that spans two lines'
  8. #原樣輸出字符串
  9. s3 = """this is long String
  10. that spans two lines
  11. """
  12. # 換行輸出字符串
  13. s4 = 'this is long String\n\
  14. that spans two lines'
  15. print "s1=",s1
  16. print "s2=",s2
  17. print "s3=",s3
  18. 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. #把unicode碼值轉化為字符串
  4. print repr(unichr( 8224))
  5. #把unicode字符串轉化為碼值
  6. print repr(ord( u'\u2020'))

 

D:chr()函數與str函數的區別:

           1. chr()函數是把一個小整數作為參數,並返回對應於ASCII單字符的字符串

           2. str()函數是把任何整數作為參數,返回一個該整數的文本形式的字符串


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM