Python学习之String

Posted zhichun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习之String相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Python 学习之《Learn Python3 The Hard Way 》第五部分学习笔记

Python 学习之《Learn Python3 The Hard Way 》第八部分学习笔记

Python 学习之《Learn Python3 The Hard Way 》第二部分学习笔记

Python 学习之《Learn Python3 The Hard Way 》第七部分学习笔记

Python 学习之《Learn Python3 The Hard Way 》第十二部分学习笔记

Python 学习之《Learn Python3 The Hard Way 》第四部分学习笔记