(python learn) 4 number&& string

We will look at the number type and string type.

Number

There are int, long , float and complex number in python.

Int, which is very simple like below.

1 >>> type(1)
2 <type 'int'>
3 >>> type(888)
4 <type 'int'>

But some times, we need to store very big int number like 999999999999, then we need long type.

1 >>> type(999999999999999999999)
2 <type 'long'>

There are different ways to define long type. You can put a 'L' or 'l' behind the data.

1 >>> type(1l)
2 <type 'long'>
3 >>> type(1L)
4 <type 'long'>

 The float is very simple to define. Just add the arthmetic point.

1 >>> type(8.0)
2 <type 'float'>

In python, we can define complex type.

1 >>> type(8j)
2 <type 'complex'>

String

There three ways to define string.

use single quotation

use double quotation

use three quotation

Usually we can use single quotation to define a string. But sometimes like below, using the single quotation will cause ambiguous.

' let's go'

So in this situtation we had better to define the string with double quotation

" let's go"

But of course you can use the "\". For example ' let\'s go'.

So what is the situtation we use """? Check below

 1 >>> a="""
 2 ... Hello Kramer
 3 ...     Nice to see you
 4 ... """
 5 >>> print(a)
 6 
 7 Hello Kramer
 8         Nice to see you
 9 
10 >>> a
11 '\nHello Kramer\n\tNice to see you\n'

Yes, the """ can help to store the formating characters.

Another very important thing about string type is that it is an sequence type. That means you can use it like array in c++/c.

For example.

1 >>> a='abcde'
2 >>> a[0]
3 'a'
4 >>> a[1]
5 'b'

So we can use this character to cut a string.

For example

1 >>> a='abcde'
2 >>> a[0:4]
3 'abcd'

Here you need to notice one thing. a[0:4] returns the  a[0] to a[3], not a[4].

Actually you can see this as an function. the first parameter tell computer from where to cut the string. The second parameter tells where is the end of the sub str. But actually it has the thrid parameter tells the step size. The default value is 1. You can use -1 means to cut the value from right to left or 2 to cut the value every 2 members.

1 >>> a='abcde'
2 >>> a[0:4:2]
3 'ac'
4 >>> a[-1:-4:-1]
5 'edc'

And if you look the code very carefully, You will find another thing. The -1 stand for the last character        

原文地址:https://www.cnblogs.com/kramer/p/2941828.html