<built-in method title of str object at 0x10dbda6b0>
字符串改为大写
print(name.upper())
HELLO WORLD
字符串改为小写
str1 = "HELLO WORLD" print(str1.lower())
hello world
使用“+”拼接字符串
print(name + " and "+str1)
hello world and HELLO WORLD
strip() / rstrip() / lstrip()
要确保字符串开头、末尾没有空白,可使用方法strip()
str1 = " hello python3 " str2 = "hello python "
print("--"+ str1.strip() + "--")
--hello python3--
要确保字符串末尾没有空白,可使用方法rstrip()
print(str2.rstrip()) ## 临时的
hello python
print("' "+ str2 + "' ")
' hello python '
要确保字符串开头没有空白,可使用方法lstrip()
print("-"+str2.lstrip())
-hello python
次方运算
print(3 ** 2)
9
print(3 ** 3)
27
避免类型错误 str()
age = 23 message = "Happy " + age + "rd Birthday"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-5bbdce04c224> in <module>
1 age = 23
----> 2 message = "Happy " + age + "rd Birthday"
TypeError: must be str, not int
message = "Happy " + str(age) + "rd Birthday"
print(message)
Happy 23rd Birthday
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!
有时候,你要将元素从列表中删除,并接着使用它的值。例如,你可能需要获取刚被射杀的外星人的 x 和 y 坐标,以便在相应的位置显示爆炸效果;在Web应用程序中,你可能 要将用户从活跃成员列表中删除,并将其加入到非活跃成员列表中。 方法pop() 可删除列表末尾的元素,并让你能够接着使用它。术语弹出 (pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name insorted(favorite_languages.keys()): print(name.title() + ", thank you for taking the poll.")
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } print("The following languages have been mentioned:") for language in favorite_languages.values(): print(language.title())
The following languages have been mentioned:
Python
C
Ruby
Python
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } print("The following languages have been mentioned:") for language inset(favorite_languages.values()): print(language.title())
The following languages have been mentioned:
Ruby
C
Python
defbuild_person(first_name, last_name, age=''): """返回一个字典,其中包含有关一个人的信息""" person = {'first': first_name, 'last': last_name} if age: person['age'] = age return person
defshow_completed_models(completed_models): """显示打印好的所有模型""" print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
defshow_completed_models(completed_models): """显示打印好的所有模型""" print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
The following models have been printed:
iphone case
robot pendant
dodecahedron
defmake_pizza(size, *toppings): """概述要制作的比萨""" print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping)
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
类
classDog(): def__init__(self, name, age): self.name = name self.age = age defsit(self): print(self.name.title() + " is now sitting!") defroll(self): print(self.name.title() + " rolled over!")
defElectricCar(Car): def__init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 deffill_gas_tank(): """电动汽车没有油箱""" print("This car doesn't need a gas tank!")
withopen('pi_digits.txt') as fp: lines = fp.readlines() pi_string = '' for line in lines: pi_string += line.rstrip() print(pi_string) print(len(pi_string))
filename = 'programming.txt' withopen(filename, 'a') as file_object: file_object.write("I also love finding meaning in large datasets.\n") file_object.write("I love creating apps that can run in a browser.\n")
异常
print(5/0)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-217-fad870a50e27> in <module>
----> 1 print(5/0)
ZeroDivisionError: division by zero
filename = 'alice.txt' try: withopen(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg)
Sorry, the file alice.txt does not exist.
分析文本
提取文本
下面来提取童话 Alicein Wonderland 的文本,并尝试计算它包含多少个单词。我们将使用方法split(),它根据一个字符串创建一个单词列表。下面是对只包含童话名”Alice in Wonderland” 的字符串调用方法split()的结果: