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()函數是把任何整數作為參數,返回一個該整數的文本形式的字符串