小方哥哥 2019-06-28
message = "Hello World!"
message 就是变量,这个变量存储了一个值。
message_1
name_length
比 length_of_persons_name
好方法跟在字符串后面调用。
name = 'bramble xu' print(name.title())
输出的结果是Bramble Xu
.
name.title()
: 能把每个单词的首字母变为大写name.upper()
: 全是大写name.lower()
: 全是小写用+
号来拼接字符。
first_name = 'bramble' last_name = 'xu' full_name = first_name + ' ' + last_name print('Hello, ' + full_name.title() + '!')
输出结果Hello, Bramble Xu!
\t
: 制表符\n
: 换行符>>> print("\tPython") Python >>> print("Languages:\n\tPython\n\tC\n\tJavaScript") Languages: Python C JavaScript
在用户登录网站的时候检查用户名是否有空白,删去空白。
'python '.rstrip()
: 删除右边空白' python'.lstrip()
: 删除左边空白' python '.strip()
: 删除两边空白要注意,这里调用strip()
方法后,并没有对原本的字符串进行更改。想要永久删除空白,必须把删除操作的结果保存到变量里。
>>> favorite_language = 'python ' ❶ >>> favorite_language = favorite_language.rstrip() >>> favorite_language 'python'
message = 'One of Python's strengths is its diverse community.'
比如这种一句话里有三个单引号,就造成了语法错误。
可以把外围的双引号用单引号代替message = "One of Python's strengths is its diverse community.“
需要注意一下除法
在Python 3.0中,’/’总是执行真除法,不管操作数的类型,都会返回包含任何余数的浮点结果;’//’执行Floor除法,截除掉余数并且针对整数操作数返回一个整数,如果有任何一个操作数是浮点数,则返回一个浮点数。
Floor除法:效果等同于math模块中的floor函数:
>>> 5//3 #1.6666666666666667 1 >>> -5//3 -2
与floor()函数类似的还有很多,比如trunc()函数:
>>> import math >>> math.trunc(-1.6) -1 >>> math.trunc(1.6) 1
>>> 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!