|
这是Python系列连载之Python语法基础的第三讲,这个连载系列尽可能用通俗的语言来讲解Python的语法基础,希望读者阅读后能轻松掌握Python!这一讲的主要内容:
#=====================================================================
1 Python中的字符串(string)
2 Python的list
3 Python的tuple
4 Python的dict
#=====================================================================
1 Python中的字符串(string)
1) Python中的字符串可以用双引号“”和单引号''表示,比如,
要表达字符串abc,要这样写:"abc"或者'abc'
但如果字符串本身含有双引号或者单引号怎么办?就用一个特殊符号"/"(backward slash)来转换。比如
要表达字符串:Let's go shopping 要这样写"Let/'s go shopping”或者'Let/'s go shopping'
要表达字符串:He said:"You win."要这样写"He said:/"You win./""或者'He said:/"You win./"'
2) Pthon字符串可以通过%号来拼接,使字符串的组合更灵活
>>> var1 = "Hey %s, how's %s" >>> var2 = ("Body", "your leg") >>> print var1 % var2 Hey Body, how's your leg
注意,%后的变量(这里是var2)必须要用()括起来
3) 把数字转换为字符串,用str()函数[1]
比如:
>>> str1 = str(1) >>> str1 '1' >>> str1 = str(1.5) >>> str1 '1.5'
4) 读取字符串(slice切片)
>>> str = "Python is Cool!" >>> str[0] 'P' >>> str[0:5] 'Pytho' >>> str[-1] '!' >>> str[-3:-1] 'ol' >>> str[:] 'Python is Cool!' >>> str[0:5:2] 'Pto'
最容易记住slice的方法是把下标看成是字符间的指针,第一个字符的左边是0,最后一个字符的右边是n(n是字符串长度),如下图:
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
[1] 也可以用backticks(`)和repr来把数字转换为字符串,但是这些方法已经在Python 3.X中被抛弃了,所以这里不介绍了 |