码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习之String

时间:2019-09-02 17:06:39      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:close   net   answer   article   arch   cti   aries   following   sts   

Strings可以想象成一个有序列的数组

#Indexing

planet = ‘Pluto‘

 

planet[0]

‘P‘

 

 

#Slicing

planet[-3:]

‘uto‘

 

#How long

len(planet)

 

String methods

 

#字母大写

 

claim = ‘Pluto is a planet

claim.upper()

 

#all lowercase 

claim.lower()

 

#search for the first index of substring

claim.index(‘plan‘)

 

Going between strings and lists : .splits and .join()

words = claim.split()

datestr=‘1956-01-31

 

year,month,day = datestr.split(‘-‘)

‘/‘.join ([month,day,year])

‘/‘.join([word.upper() for word in words])

 

如过数值是non-string object,则可以先使用str 转换数值

str(position)

 

format占位符

 

This is getting hard to read and annoying to type. str.format() to the rescue

"{}. you‘ll always be the{}th planet to me".format{planet,position}

 

 

检测元组中是否有数值:

seq = [‘one‘, ‘two‘, ‘three‘]

if ‘one‘ in seq:
  print True

 

Dictionraries

 

 

numbers={‘one‘:1, ‘two‘:2, ‘three‘: 3}

numbers[‘one‘]

1

 

numbers[‘eleven‘]=11

numbers

 

练习一:

A researcher has gathered thousands of news articles. But she wants to focus her attention on articles including a specific word. Complete the function below to help her filter her list of articles.

Your function should meet the following criteria

- Do not include documents where the keyword string shows up only as a part of a larger word. For example, if she were looking for the keyword “closed”, you would not include the string “enclosed.”
- She does not want you to distinguish upper case from lower case letters. So the phrase “Closed the case.” would be included when the keyword is “closed”
- Do not let periods or commas affect what is matched. “It is closed.” would be included when the keyword is “closed”. But you can assume there are no other types of punctuation.

 

 

Answer:

Solution:

def word_search(doc_list, keyword):
  indices = []
  for i,doc in enumerate(doc_list):
    temp=doc.split()
    word = [item.strip(‘.,‘).lower() for item in temp]
    if keyword.lower() in word:
    indices.append(i)
  return indices


Python学习之String

标签:close   net   answer   article   arch   cti   aries   following   sts   

原文地址:https://www.cnblogs.com/zhichun/p/11444972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!