【Python】编程小白的第一本python(基础中的基础)

一、变量

如果不知道变量是什么类型,可以通过type()函数来查看类型,在IDE中输入:

print(type(word))

  另外,由于中文注释会导致报错,所以需要在文件开头加一行魔法注释

#coding:utf-8

 二、print

  

 

 

   要注意语法问题,使用英文标点符号、大小写不能出错、空格不能少。

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

三、字符串

  (1)表示:单引号、双引号、三引号

  (2)字符串可以相加、相乘等等做运算

  (3)字符串的分片与索引

可以通过 string[x] 的方式进行索引、分片,也就是加一个[]。字符串的分片实际上可以看作是从字符串中找出来你想要截取的东西,复制出来一小段你要的长度,储存在另一个地方,而不会对字符串这个源文件改动。

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[5:])
'me is Mike'
print(name[:5])
'My na'

 

   (4)字符串方法replace()

    replace方法的括号中,第一个代表要被替换掉的部分,第二个代表将要替换成什么字符

    举例一:

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

    举例二(模拟电话号码联想功能):

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

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

    会得到结果

 

   (5)字符串格式化符.format()

    1)填空题批量处理。以下例子输出:With a word she can get what she came for.

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'))

    2)下列代码可以填充网址中空缺的数据

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

 

posted on 2019-11-20 21:47  Hinwya  阅读(221)  评论(0编辑  收藏  举报

导航