# 第三章 变量与字符串

## 3.2 变量

《银河系漫游指南》里面说“生命、宇宙以及任何事情的终极答案是42”，如果用编程语言来表达的话，就是如下等式，一个叫做 “answer” 的变量被赋值为 42 。正如每个人都有姓名一样，变量的名字叫做标识符。

a = 12

## 3.3 print()

file = open('/Users/yourname/Desktop/file.txt','w')
file.write('hello world!')

## 3.4 字符串

### 字符串的基本用法

what_he_does = ' plays '
his_instrument = 'guitar'
his_name = 'Robert Johnson'
artist_intro = his_name + what_he_does + his_instrument

print(artist_intro)

Robert Johnson plays guitar

num = 1
string = '1'

print(num + string)

num = 1
string = '1'
num2 = int(string)

print(num + num2)

words = 'words' * 3
print(words)

word = 'a loooooong word'
num = 12
string = 'bang!'
total = string * (len(word) - num)  #等价于字符串'bang!'*4
print(total)

### 字符串的分片与索引

name = 'My Name is Mike'

print(name[0])
'M'
print(name[-4])
'M'
print(name[11:14])  # from 11th to 14th, 14th one is excluded
'Mik'
print(name[11:15])  # from 11th to 15th, 15th one is excluded
'Mike'
print(name[5:])
'me is Mike'
print(name[:5])
'My Na'

: 两边分别代表着字符串的分割从哪里开始，并到哪里结束。

name[11:14] 为例，截取的编号从第11个字符开始，到位置为14但不包含第14个字符结束。

word = 'friends'
find_the_evil_in_your_friends =  word[0] + word[2:4] + word[-3:-1]
print(find_the_evil_in_your_friends)

'http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg'
'http://ww1.site.cn/85cc87jw1ex23yhwws5j20jg0szmzk.png'
'http://ww2.site.cn/185cc87jw1ex23ynr1naj20jg0t60wv.jpg'
'http://ww3.site.cn/185cc87jw1ex23yyvq29j20jg0t6gp4.gif'

url = 'http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg'
file_name = url[-10:]

print(file_name)

### 字符串的方法

Python 是面向对象进行编程的语言，而对象拥有各种功能、特性，专业术语称之为——方法（Method）。为了方便理解，我们假定日常生活中的车是“对象”，即car。然后众所周知，汽车有着很多特性和功能，其中"开"就是汽车一个重要功能，于是汽车这个对象使用“开”这个功能，我们在 Python 编程中就可以表述成这样：car.drive()

phone_number = '1386-666-0006'
hiding_number = phone_number.replace(phone_number[:9],'*' * 9)
print(hiding_number)

search = '168'
num_a = '1386-168-0006'
num_b = '1681-222-0006'

print(search + ' is at ' + str(num_a.find(search) + 1) + ' to ' + str(num_a.find(search) + len(search)) + ' of num_a')
print(search + ' is at ' + str(num_b.find(search) + 1) + ' to ' + str(num_b.find(search) + len(search)) + ' of num_b')

168 is at 6 to 8 of num_a
168 is at 1 to 3 of num_b

### 字符串格式化符

____a word she can get what she ____ for.

A.With    B.came

print('{} a word she can get what she {} for.'.format('With','came'))
print('{preposition} a word she can get what she {verb} for'.format(preposition = 'With',verb = 'came'))
print('{0} a word she can get what she {1} for.'.format('With','came'))

city = input("write down the name of city:")
url = "http://apistore.baidu.com/microservice/weather?citypinyin={}".format(city)