0
点赞
收藏
分享

微信扫一扫

Python学习笔记(6)


Python学习笔记(6)



1)Sequence


Sequence是一对象,一个接一个地保存多种数据项。Python中Sequence有几种不同类型。


下面先看两种Sequence基本类型:字符串和列表


在字符串中访问单个字符:


用for循环迭代字符串,语法如下:


for variable in string:

 statement

 statement

 etc.


例子:


>>> name = 'Juliet'

>>> for ch in name:

 print ch

J

u

l

i

e

例2:


# This program counts the number times

# the letter T appears in a string.

def main():

  count = 0

  my_string = raw_input('Enter a sentence: ')

  for ch in my_string:

  if ch == 'T' or ch == 't':

  count +=1

  print 'The letter T appears',count,'times.'

main()



使用索引访问字符串中的单个字符


字符串的每个字符都有一个序号,表示它在字符串中的位置。


例:


>>> my_string = 'Roses are red'

>>> ch = my_string[6]

>>> ch

'a'

>>> print my_string[0],my_string[6],my_string[10]

R a r


还可以用负数做序号,-1表示字符串最后一个字符,-2表示倒数第2个字符,依次类推。


>>> my_string[-1]

'd'

>>> my_string[-2]

'e'


序号错误


序号有范围,如‘Boston’字符串的序号为0~5以及-1~-6。超出此范围则IndexError。


例:

>>> city='Boston'

>>> print city[6]

Traceback (most recent call last):

  File "<pyshell#11>", line 1, in <module>

  print city[6]

IndexError: string index out of range



字符串分割


格式如下:


string[start:end]


例:


>>> full_name = 'Patty Lynn Smith'

>>> middle_name = full_name[6:10]

>>> print middle_name

Lynn


例:


login.py


# The get_login_name function accepts a first name,

# last name, and ID number as arguments. It returns

# a system login name.

def get_login_name(first,last,idnumber):

  # Get the first three letters of the first name.

  # If the name is less than 3 characters, the

  # slice will return the entire first name.

  set1 = first[0:3]

  # Get the first three letters of the last name.

  # If the name is less than 3 characters, the

  # slice will return the entire last name.

  set2 = last[0:3]

  # Get the last three characters of the student ID.

  # If the ID number is less than 3 characters, the

  # slice will return the entire ID number.

  set3 = idnumber[-3:]

  # Put the sets of characters together.

  login_name = set1+set2+set3

  return login_name


P14.py


import login

def main():

  first = raw_input('Enter your first name: ')

  last = raw_input('Enter your last name: ')

  idnumber = raw_input('Enter your student ID number: ')

  # Get the login name.

  print 'Your system login name is:'

  print login.get_login_name(first, last, idnumber)

main()

测试子串是否在字符串中


用in 或 not in



列表的方法


append(item) 在列表最后添加item


index(item) 返回序号指定的元素


insert(index, item) 在指定序号后插入item


sort() 列表按从小到大的顺序排序


remove(item) 删除列表中第一个出现item的项


reverse() 列表反序


例:


>>> my_list = [1,2,3,4,5]

>>> del my_list[2]

>>> print my_list

[1, 2, 4, 5]


>>> my_list=[5,4,3,123,50,40,30]

>>> print 'The lowest value is',min(my_list)

The lowest value is 3

>>> print 'The highest value is', max(my_list)

The highest value is 123



举报

相关推荐

Python学习笔记-6

Jenkins学习笔记6

Java学习笔记6

学习笔记-kotlin(6)

学习笔记【5+6】

0 条评论