2014年11月9日

Python Study (5)– String Type


Introduce to string type 


ASCII is a sample form of Unicode text, but many text may be not non-English-text source.File working in two modes are  text and bytes ,We need to understand differnt of String of object type in Python3.X and Python 2.X. 

Python3.X :
    (1) str           : handle text of Unicode form
    (2) bytes       : handle binary data
    (3) bytearray : handle mutable variant of bytes
Python2.x:
   (1) str           :  handle 8-bits text and binary data
   (2) unicode    :  hanlde Unicode text
   (3) bytearray  : handle mutable variant of bytes. ( support 2.6 or later)


1.String Basics 
Everything is string.String can be used to represent informations of all kinds(e.g. profile, song…), these informations can be encoded as text or bytes.  


2.String Literals

In python, String function handle various data types.
quote mark description
single quote
‘temp’s’
double quote
“temp’s”
triple quotes “”” mutiline…  ”””
  ‘’’mutilne… ‘’’
raw string r”data”
escape sequences “s\tdat\n”
bytes b’sp\x01’
unicode u’eggs\u001’

Problem 1. single and double-quoted string are the same ?
       In python, single- and double-quote  characters are interchangeable. string
       literals is written enclosed in either two single or two double quotes.

Example:


>>> 'apple',"apple"
('apple', 'apple')

>>> 'Tom"s apple',"Tom's apple"  //embed a quote
('Tom"s apple', "Tom's apple")

>>> 'Tom\'s apple',"Tom\'s apple" //use escape quote
("Tom's apple", "Tom's apple")




Escape  


Escape Description
\n
Newline
\t
tab
\xhh
hex value
\o
octal value
\’
single quote
\”
double quote
\\
backslash(\)
\0
null: binary 0 character
\N{id}
Unicode database ID
\uhhhh
Unicode character with 16-bit hex value
\uhhhhhhhh
Unicode character with 32-bit hex value

Example:

>>> “abc\ndef\t ghi ”
'abc\ndef\t ghi'
>>> print(“abc\ndef\t ghi ”)
’abc
   def    ghi



Basic Operations 

Operation Description
len(str) return the length of a string or size of the string in the memory
str + str return concatenate two string to create new string
str * n return  adding a string to itself a number of times
[start:end] return slicing the string
image
[start:end:step] return slicing the string by step
Example:
             s = “abcdefghijklmnopqrstuvwxyz”


>>> s = "abcdefghijklmnopqrstuvwxyz"
>>> len(s)
26

>>> s+"1234567890"
'abcdefghijklmnopqrstuvwxyz1234567890'

>>> s*2    
'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'
>>> s[0]
'a'
>>> s[-2]
'y'

#slicing>>> s[0]
'a'
>>> s[-1]
'z'
>>> s[1:]         #get all elements beyond the first
'bcdefghijklmnopqrstuvwxy'
>>> s[3:6]
'def'
>>> s[:-1]   # get all elements unitl the last

Note: s[0] fetches the string at offset 0 from the left and return “a”;s[-1] gets the string at offset 1 back from the end.
String conversion 

In python, if the string looks like number and you want to add a number and the string together. it will happe a error(TypeError) so you need to convert the string to integer.


>>> "30"+1
Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    "30"+1
TypeError: Can't convert 'int' object to str implicitly




These are String conversion tools

conversion Description
int(str) return converted integer
int(str, base=10) return converted integer by base
str(obj) return converted string
repr(obj) return code string,
float(text) return  floating-point-number
ord(str) it only convert a single character to integer
chr(int) an integer code convert to the correspanding character
bin(int) return binary
Example:
(1) A number and a string add together, the string is converted to integer.

(2) A number and a string add together, the number is converted to string.
(3) A string looks like a  float-point-number, the string is conveted to float.

   a = 1, b = ”2”, c = “3.14”


>>> a = 1
>>> b = "2"
>>> c = “3.14”
>>> a + int(b)      # (1) convert to integer
3

>>> str(a) + b     # (2) convert to string
'12'


>>> float(c)
3.14

Example :
    (1) single character convert to integer code
    (2) integer convert to single character




Example:
   (1) binary to integer
   (2) integer to binary



>>> int('1111',2)
15

>>> bin(15)
'0b1111'


String function 



function Description
capitalize() retrun the first character of the string is  capitalized
casefold() return the string is lowercased
center(int width)
encode(encoding=”utf8”) Return an encoded version of the string as a bytes object.
find(str) return index in the string where substring is found
index(str) like find()
isalpha() return true if all characters are alphabestic in the string
isdecimal() return true if all characters are decimal in the string
isdigit() return true if all characters are digits in the string
lower() like casefold()
split() return a list of the words in the stirng by sep as the delimiter string.
zfill(int width) return the string filled with ‘0’













沒有留言:

張貼留言