當前位置:首頁 » 編程語言 » python搜索字元串

python搜索字元串

發布時間: 2023-06-09 01:05:07

python字典,如何查找值中包含指定字元串的鍵

1、說明python中檢測字典的鍵中是否含有某串字元,便利字典鍵值,再判斷字元串是否在鍵值中即可。2、示例代碼:# 定義一個字典dic = {'1984/1/2': 123, '1984/1/3': 0, '1985/1/1': 156}# 遍歷字典鍵中是否包含1984for key in dic: if '1984' in key: print('鍵值中包含字元串"1984"') # 或者需要的其它操作 else: print('鍵值中不包含字元串"1984"')3、執行結果:鍵值中包含字元串"1984"鍵值中不包含字元串"1984"鍵值中包含字元串"1984"

4、其它說明:python使用for in直接操作字典就是遍歷字典的鍵值,python使用in操作來判斷字元串中是否包含子串最方便,要優於使用字元串的函數index或者find。

index函數在找不到子串時會報錯,find函數會返回-1。

❷ 如何用Python語言實現在一個文件中查找特定的字元串

用正則表達式

>>>s='helloworld'
>>>importre
>>>re.search('wor',s)
<_sre.SRE_Matchobject;span=(6,9),match='wor'>

❸ python 文本文件中查找指定的字元串

編寫一個程序,能在當前目錄以及當前目錄的所有子目錄下查找文件名包含指定字元串的文件,並列印出絕對路徑。
import os
class SearchFile(object):

def __init__(self,path='.'):
self._path=path
self.abspath=os.path.abspath(self._path) # 默認當前目錄

def findfile(self,keyword,root):
filelist=[]
for root,dirs,files in os.walk(root):
for name in files:
fitfile=filelist.append(os.path.join(root, name))
#print(fitfile)
print(os.path.join(root, name))
#print(filelist)
print('...........................................')
for i in filelist:
if os.path.isfile(i):
#print(i)
if keyword in os.path.split(i)[1]:
print('yes!',i) # 絕對路徑
#else:
#print('......no keyword!')

def __call__(self):
while True:
workpath=input('Do you want to work under the current folder? Y/N:')
if(workpath == ''):
break
if workpath=='y' or workpath=='Y':
root=self.abspath # 把當前工作目錄作為工作目錄
print('當前工作目錄:',root)
dirlist=os.listdir() # 列出工作目錄下的文件和目錄
print(dirlist)
else:
root=input('please enter the working directory:')
print('當前工作目錄:',root)
keyword=input('the keyword you want to find:')
if(keyword==''):
break
self.findfile(keyword,root) # 查找帶指定字元的文件

if __name__ == '__main__':
search = SearchFile()
search()

❹ 如何用Python來進行查詢和替換一個文本字元串

1、說明
可以使用find或者index來查詢字元串,可以使用replace函數來替換字元串。
2、示例
1)查詢
>>> 'abcdefg'.find('cde')
結果為2
'abcdefg'.find('acde')
結果為-1
'abcdefg'.index('cde')
結果為2
2)替換
'abcdefg'.replace('abc','cde')
結果為'cdedefg'
3、函數說明
1)find(...)
S.find(sub[, start[, end]]) -> int
返回S中找到substring sub的最低索引,使得sub包含在S [start:end]中。 可選的 參數start和end解釋為切片表示法。
失敗時返回-1。
2)index(...)
S.index(sub[, start[, end]]) -> int
與find函數類似,但是當未找到子字元串時引發ValueError。
3)replace(...)
S.replace(old, new[, count]) -> str
返回S的所有出現的子串的副本舊換新。 如果可選參數計數為給定,只有第一個計數出現被替換。

❺ python 如何連續查找字元串

python的字元串可以看做是數組的

所以比如mystr = "what is your name"

newstr = mystr

if newstr.find("a") >= 0:

newstr = newstr[newstr.find("a"):] #這是後newstr就是第一個a開始之後的字元串

如果不需要包含第一個找到的a,那麼可以這樣:
while newstr.find("a") >= 0:

newstr = newstr[newstr.find("a")+1:] #這樣一致到newstr裡面不包含a為止

❻ Python API快餐教程(1) - 字元串查找API

字元串是7種序列類型中的一種。
除了序列的操作函數,比如len()來求字元串長度之外,Python還為字元串提供豐富到可以寫個編輯器的API.

首先,下面的查找API都是為了查找位置,或者查一共有幾次這樣的操作。
如果只是想判斷一個字元串是不是另一個字元串的子串的話,使用序列的in運算符就可以了。
例:

原型:str.count(sub[, start[, end]])

字元串的count函數可以數出來有多少次匹配,我們看個例子,有5個ha和3個hei

輸出為5和2.
haha只能匹配兩次。

再加上擴展參數:

find函數的行為是,如果能找到,則返回在序列中的坐標,如果找不到,則返回-1. rfind是從右向左查找。我們來看例子:

輸出值為0和6.

找不到的例子:

輸出值都是-1.

完整形式:

index和rindex的功能與find和rfind基本上一致,除了在找不到時會拋出ValueError異常而不是返回-1.

例:

所以我們需要加try...except語句來處理之:

有時候,我們希望做從頭匹配或者匹配尾部。這時候就要用到startswith函數和endswith函數。例:

這兩個返回值均為True.

如果需要更復雜的匹配,還是需要正則表達式。與Java等語言不同,Python中的正則表達式有專門的模塊,字元串的API不負責這個事情。

❼ python 查找字元串並將其替換

f1=open('J:/wenjian/1/1.txt','r')
for line in f1
你這里是不是少了點什麼,f1隻是文件句柄,需要執行讀操作才能遍歷,
調用readlines()

確實有更好的代碼,那就是使用re.sub,它同時包含了查找和替換兩步的操作,
而不是像你寫的那樣的字元串比較性能那麼低

❽ python 文本文件中查找指定的字元串

def find(lists):
for list0 in lists:
if list0.find('set internet Active')>=0:
if list0.find('#')>=0:
continue
else:
return 0 #有一行不帶#號的set internet Active,那麼返回0
return -1 #若沒有不帶號的set internet Active,那麼返回-1

if __name__=='__main':
lists = ['set internet Active','#set internet Active','# set internet Active']
#lists 是從文件中讀出內容的列表
findout=find(lists) #調用函數
print(findout) #列印結果

❾ Python中檢索字元串的方法有哪些呢

你還可以用更靈活的 regular 正則式
search()和match(),用起來更靈活
import re
str = "Welcome to my world. I have 12 apples."
if re.search(r"world", str).group() != "" :
print("match! ")

str = "abcABC"
if re.match(r"[a-zA-Z]+", str):
print("match! ", re.search(r"[A-Z]+", str).group())
else:
print("ummatch! ")

熱點內容
用於打開ftp連接的應用程序 發布:2025-02-14 01:23:39 瀏覽:706
網站會員注冊源碼 發布:2025-02-14 01:09:45 瀏覽:657
小火山視頻密碼是什麼 發布:2025-02-14 01:09:40 瀏覽:505
我的世界手機創的伺服器電腦能進嗎 發布:2025-02-14 01:08:16 瀏覽:163
eclipseandroid運行 發布:2025-02-14 00:54:57 瀏覽:897
雲伺服器安全策略 發布:2025-02-14 00:54:07 瀏覽:289
小米手機如何更改賬號密碼 發布:2025-02-14 00:48:48 瀏覽:572
我的世界如何導出伺服器 發布:2025-02-14 00:48:39 瀏覽:722
工業伺服器機箱怎麼樣 發布:2025-02-14 00:29:15 瀏覽:86
英朗壓縮機 發布:2025-02-14 00:29:12 瀏覽:678