变量
message = "Hello world!"
print(message)
message = "Hello Python world!"
print(message)
输出结果:
Hello world!
Hello Python world!
在程序中可以随时地去修改变量的值,而Python也始终记录变量的最新值。
字符串
在Python中用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号:
"This is a string."
'This is also a string.'
这样你就可以在字符串中包含引号或撇号:
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
"One of Python's strengths is its diverse and supportive community."
使用方法修改字符串的大小写
对于字符串,可执行的最简单的操作之一是修改其中的单词的大小写:
name = "ada lovelace"
print(name.title())
运行它将看到输出:
Ada Lovelace
还有其他几个很有用的大小写处理方法。例如,要将字符串改为全部大写或全部小写,可以像下面这样做:
name = "Ada Lovelace"
print(name.upper())
print(name.lower())
这些代码的输出如下:
ADA LOVELACE
ada lovelace
拼接字符串
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
Python可以使用’+'来拼接字符串,输出结果如下:
ada lovelace
换行符与制表符
print("Languages:\n\tPython\n\tC\n\tJavaScript")
输出结果:
Languages:
Python
C
JavaScript
删除空白
Python能够找出字符串开头和末尾多余的空白。要确保字符串末尾没有空白,可使用方法rstrip() 。
>>> favorite_language = 'python '
>>> favorite_language
'python '
>>> favorite_language.rstrip()
'python'
>>> favorite_language
'python '
还可以剔除字符串开头的空白,或同时剔除字符串两端的空白。为此,可分别使用方法lstrip() 和 strip() :
>>> favorite_language = ' python '
>>> favorite_language.rstrip()
' python'
>>> favorite_language.lstrip()
'python '
>>> favorite_language.strip()
'python'
数字
在Python中,可对整数执行加( + )减( - )乘( * )除( / )运算。
>>> 2 + 3
5
>>> 3 - 2
1
>>> 2 * 3
6
>>> 3 / 2
1.5
在终端会话中,Python直接返回运算结果。Python使用两个乘号表示乘方运算:
>>> 3 ** 2
9
>>> 3 ** 3
27
>>> 10 ** 6
1000000
在这些示例中,空格不影响Python计算表达式的方式,它们的存在旨在让你阅读代码时,能迅速确定先执行哪些运算。
非字符串转字符串
可调用函数 str() ,它让Python将非字符串值表示为字符串:
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
输出结果为:
Happy 23rd Birthday!
注释
在Python中,单行注释用井号#标识,单行或多行注释用三个单引号 ‘’’ 或者三个双引号 “”" 将注释括起来。