Python编程 从入门到实践

1 命名

  • Golang官方是建议采用驼峰命名,如getName;
  • Python官方是约定采用小写字母,并使用下划线来表示空格,如get_name

2 字符串

  • Golang里,单引号是byte类型,双引号是字符串类型
  • Python里,不管单引号还是双引号,两者都是字符串类型

3 python字符串函数

  • title() 将字符串每个单词的开头都改成大写

name = "ada lovelace"

print(name.title())    //  输出 Ada Lovelace

  • upper() 将字符串修改为全部大写
  • lower() 将字符串修改为全部小写
  • rstrip() 删除字符串末尾的空白
  • lstrip() 删除字符串开头的空白
  • strip() 删除字符串开头和末尾的空白

favorite_language = "  Python "
print("["+favorite_language.rstrip()+"]")    // [  Python]
print("["+favorite_language+"]")   // [  Python ]
print("["+favorite_language.lstrip()+"]")  // [Python ]
print("["+favorite_language.strip()+"]")  // [Python]

4 除号

  • Golang里,除号( / ) 是返回结果的整数部分,如 3/2 值为1
  • Python里,除号( / ) 是返回整个结果,如 3/2 值为1.5 , 4/3 = 1.33333

5 str( ) 将非字符串表示为字符串

age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)

6  注释

  • Golang里,注释用 "//" 和 "/* */"
  • Python里,注释用 "#"

7 Python之禅

>> 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!