Python学习(三) 输出任意格式的字符串以及字符串的切片

时间:2023-03-09 15:40:01
Python学习(三) 输出任意格式的字符串以及字符串的切片

在Python中想要输出一句话,如下

 a='hello world'
print a
//打印出的是hello world print 'hello \n world'
//打印出的是
//hello
//world
print '''hello
world
good
bye'''
//打印出的是
//hello
//world
//good
//bye

  如果想要输出换行的字符串,可以再字符串中添加转义字符 '\n',或者使用''' 或"""将有格式输出的字符串包裹起来。

   另外''' 或者""" 还有多行注释的作用。

  字符串的切片

  

 str='abcde'
print a[0]
//输出a
print a[1]
//输出b
print a[0]+a[1]
//输出ab 切片:
print str[1:4]
//输出bcd
print str[1:]
//输出bcde
print str[1::2]
//输出bd
print str[-1:-4:-1]
//输出edc str[x:y:z] 其中str是字符串 ,x 是切片起始点,y是切片终点,z是步长 所以用Python很容易实现字符串的反转
print str[-1:-6:-1]
//输出edcba