You are on page 1of 4

字串疊加

str1="看好"
str2="看壞"
str3=str1+"-"+str2
print(str3)

分割字串

str1 = '1-2-3'
str2 = str1.split('-')
print(str2)
print(len(str2))
print(str2[0])

取代字串中空格

str1= " Demo Example "


str2=str1.replace(" ", "")

找字串內是否有任一關鍵字

keyword11=["109 年合併","109 年綜合","109 年獲利"]

keyword=keyword11

for row in range(2,sh1.max_row):


str1=sh1.cell(row,1).value
if any(e in str1 for e in keyword):
sh2.cell(write_row,1).value=sh1.cell(row,1).value
找字串中的數字
import re

a = "台泥(1101)損益表 列表 111 年"


b=a.split()
c=re.findall('[0-9]+',b[0])

print(c)

找字串中特定文字所在位置
s = '半年股利:現金 8 元、股票 0.5 元'
c1 = '股票'
print(s.find(c))

c2 = '股票股利'
print(s.find(c1))

#若找不到該文字,find 函式會回傳-1

找股市公告中的數字

import re

temp_string = "尚茂 110 年虧損 3100 萬元,每股稅後 -0.66 元"

c=re.findall(r'-?\d+\.?\d*', temp_string)
print(len(c))
print(c[len(c)-1])

得到字串中的股號及股名
a = "燁聯(9957)董監持股"
for i in range(0,len(a)):
if a[i]=="(":
index1=i
#print(index1)
break

c=a[index1+1:index1+5]
print(c)

b=a[0:index1]
print(b)

判斷文字是否為小數

if str.replace(".","").isdigit():

判斷儲存格是否為數字(取代負號及小數點)
import re

for i in range(2,sh1.max_row+1):
str1=str(sh1.cell(i,1).value)

if str1 is not None:


if re.sub(r'[-.]',"",str1).isdigit():
print(sh1.cell(i,1).value)
if float(sh1.cell(i,1).value)<0:
fill = PatternFill(fill_type = "solid", fgColor="8CFF40")
sh1.cell(i,1).fill=fill
if sh1.cell(i,1).value>=20:
fill = PatternFill(fill_type = "solid", fgColor="FFFF00")
sh1.cell(i,1).fill=fill
判斷儲存格是否為空格(None)
#調整格式

for i in range(2,sh2.max_row+1):
str1=str(sh2.cell(i,1).value)
if str1 is not None:
if "營增" in str1:
for j in range(2,sh2.max_column+1):
if sh2.cell(i,j).value>=20:
fill = PatternFill(fill_type = "solid", fgColor="FFB6C1")
sh2.cell(i,j).fill=fill
if sh2.cell(i,j).value<=-20:
fill = PatternFill(fill_type = "solid", fgColor="8CFF40")
sh2.cell(i,j).fill=fill

尋找是否有特定文字

string = "This contains a word"


if "word" in string:
print("Found")
else:
print("Not Found")

You might also like