Python学习之String,,Strings可以想
Python学习之String,,Strings可以想
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 实用技巧,,模块相关导入模块时,
- 对当今Python 快速发展的研究与展望,,对当今Python
- python_readlines(),,# -*- codi
- python连接mysql,,import pym
- Python知乎热门话题爬取,,本例子是参考崔老师的
- 【Python requests多页面爬取案例】 񩲝,,原文:
- Python--格式化cookie为字典类型,,import req
- 如何查看本机安装的python支持哪种.whl文件,,第一步:
- python接口自动化框架_初级,,1、前提:pytho
- Python3 使用filetype包查找指定目录中所有损坏的文件(图
评论关闭