1.creating a string
(1)单引号双引号都可以,但要注意下面的这种情况。下面这个语句会报错,因为I am的缩写的单引号会和字符串开头的‘一起构成一对引号,让这个字符串提前结束
# Be careful with quotes!
' I'm using single quotes, but this will create an error'
这种情况改成双引号就好:
"Now I'm ready to use the single quotes inside a string!"
2.printing a string
使用\n来另起一行
print('Use \n to print a new line')
print('\n')
3.String Basics
len()函数来对字符串进行长度的测量,其中包括逗号和空格也算进去的,如:
len('Hello World')
长度为11
4.String Indexing
(1)索引从0开始,比如要获取第一个字母
# Show first element (in this case a letter)
s[0]
结果就是 H
(2)要获取从第二个元素之后的,如下:
# Grab everything past the first term all the way to the length of s which is len(s)
s[1:]
结果为 ello World
(3)如下的代码能取出第一个到
# Grab everything UP TO the 3rd index
s[:3]
输出结果为 'Hel'
这里需要指出:python的索引是前闭后开的,所以取不到3
(4)倒叙索引 由于左闭右开,所以这里-1处的d根本取不到
# Grab everything but the last letter
s[:-1]
输出结果为: 'Hello Worl'
要想把整句取到可以这样写:
#Everything
s[:]
输出为hello world
(5) 最后那位为步长
5.string properties (性能)
(1)string具有稳定性,是不能被赋值改变的,s[0]= ’x' 这样是错误的语法,但是可以在原来的string上再加上一段字符串,比如下面:
# Concatenate strings!
s + ' concatenate me!'
输出结果为Hello World concatenate me!
(2)我们可以利用这种string的稳定性,如下:
6.basic built-in string methods