python基本操作

一、注释

1.单行注释:

Python中单行注释以 # 开头。

2.多行注释:

多个 # 号,还有 ''' (三个单引号)和 """(三个双引号)【python中单引号和双引号使用完全相同】

如:注释掉中间两行:

print("I ")
'''
print("like ")
print("you!")
'''
print("**")
print("I ")
"""
print("like ")
print("you!")
"""
print("**")

【print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=""

print("I")
print("like",end=" " )
print("you!")

输出:

I
like you!

二、多行语句

Python 通常是一行写完一条语句,但如果语句很长,可以使用反斜杠(\)来实现多行语句,例如:

total = "I " + \
        "like " + \
        "you"
print(total)

在 [], {}, 或 () 中的多行语句,不需要使用反斜杠(\),例如:

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

三、字符串(String)

  • python中单引号和双引号使用完全相同。
  • 使用三引号('''或""")可以指定一个多行字符串。
  • 转义符 '\'
  • 反斜杠可以用来转义,使用r可以让反斜杠不发生转义。 如 r"this is a line with \n" 则\n会显示,并不是换行。
  • 按字面意义级联字符串,如"this " "is " "string"会被自动转换为this is string。
  • 字符串可以用 + 运算符连接在一起,用 * 运算符重复。
  • Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
  • Python中的字符串不能改变。
  • Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
  • 字符串的截取的语法格式如下:变量[头下标:尾下标]

如:

str='Runoob' 
print(str)                 # 输出字符串
print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
print(str[0])              # 输出字符串第一个字符
print(str[2:5])            # 输出从第三个开始到第五个的字符
print(str[2:])             # 输出从第三个开始的后的所有字符
print(str * 2)             # 输出字符串两次
print(str + '你好')        # 连接字符串
 
print('------------------------------')
 
print('hello\nrunoob')      # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob')     # 在字符串前面添加一个 r,表示原始字符串,不会发生转义

输出:

Runoob
Runoo
R
noo
noob
RunoobRunoob
Runoob你好
------------------------------
hello
runoob
hello\nrunoob

四、同一行显示多条语句

Python可以在同一行中使用多条语句,语句之间使用分号(;)分割。如:

import sys; x = 'runoob'; sys.stdout.write(x + '\n')

猜你喜欢

转载自blog.csdn.net/u013925378/article/details/83753415