Code
= "Hello , world!"
message
# 直接打印 或 print()
messageprint(message)
Hello , world!
规则:
创建一个名为message
的变量(variable),"Hello python world!"
是变量指向的值(value)。
= "Hello , world!"
message
# 直接打印 或 print()
messageprint(message)
Hello , world!
用引号引起的是字符串,其中引号既可以是双引号,也可以是单引号。
"This is a string"
'This is also a string'
"他说'世界是你们的,也是我们的,但终究是你们的'。流泪\u1000"
"他说'世界是你们的,也是我们的,但终究是你们的'。流泪က"
例如,在函数调用print()
中,方法 title()
出现在变量名后面。
method是Python对数据执行的操作,在name.title()
中,name
是变量名,句点.
让Python对name变量执行方法title()
指定的操作。
= "ada lovelace"
name
nameprint(name)
print(name.title())
print(name.upper())
print(name.lower())
name
ada lovelace
Ada Lovelace
ADA LOVELACE
ada lovelace
'ada lovelace'
method | 作用 |
---|---|
title() |
以首字母大写的方式显示每个单词 |
upper() |
使字母全大写 |
lower() |
使字母全小写 |
strip() |
删除左右空白 |
rstrip() |
删除右空白 |
lstrip() |
删除左空白 |
removeprefix(x) |
删除前缀x |
f字符串,在左"
之前添加字母f
(format设置格式),再将变量名放入{}
内。
= "ada"
first_name = "lovelace"
last_name = f"{first_name} {last_name}"
full_name print(full_name)
print(f"Hello,{full_name.title()}!")
= f"Hello,{full_name.title()}!"
greet print(greet)
= "Eric"
name = f"Hello {name},would you like to learn some Python today?"
message message
ada lovelace
Hello,Ada Lovelace!
Hello,Ada Lovelace!
'Hello Eric,would you like to learn some Python today?'
空白泛指任何非打印字符,如空格、制表符、换行符。
print("Python")
print("\tPython")
print("Languages:\n\t1.Python\n\t2.R\n\t3.C")
Python
Python
Languages:
1.Python
2.R
3.C
= " python "
language
language#删除右空白
language.rstrip()
#删除左空白
language.lstrip()
#删除左右空白
language.strip()
'python'
但这种删除是暂时的
language
' python '
= "https://github.com"
github_url "https://")
github_url.removeprefix(
file = "basics.txt"
file.removesuffix(".txt")
'basics'
可执行加+
、减-
、乘*
、除/
、整除//
、乘方**
、求模(取余数) %
运算。
2+3
5-2
2*3
8/2
8//2
9//2
5**2
10%3
print(5+3)
print(9-1)
print(4*2)
print(16//2)
print(2**3)
8
8
8
8
8
0.2+0.5
2*0.4
0.2+0.1
3*0.1
4/2
1+2.0
3.0**2
9.0
位数分组
= 14_000_000_000
x x
14000000000
用逗号分隔
= 1,2.0,4**2
x,y,z
x
y z
16
常量constant
变量名全大写字母表示常量。
= 9
FAVORITE_NUMBER = f"My favorite number is {FAVORITE_NUMBER}"
message print(message)
My favorite number is 9
import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!