String(字符串)
在Python中,字符串用单引号 ' 或双引号 " 括起来,同时使用反斜杠 \ 转义特殊字符。
字符串截取的语法格式如下:
变量[头下标:尾下标]
索引值从0开始,-1是从末尾的开始位置
加号 + 是字符串的连接符,星号 * 表示复制当前字符串,与之结合的数字为复制的次数。
实例如下:
str = 'hello world'
print (str) # 输出字符串
print (str[0:-1]) # 输出第一个到倒数第二个的所有字符
print (str[0]) # 输出字符串第一个字符
print (str[2:5]) # 输出从第三个开始到第五个的字符
print (str[2:]) # 输出从第三个开始的后的所有字符
print (str * 2) # 输出字符串两次,也可以写成 print (2 * str)
print (str + "handsome") # 连接字符串
执行结果为:
hello world
hello worl
h
llo
llo world
hello worldhello world
hello worldhandsome
在Python中,