iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 7
0

操作層面分為取出資料、如何走訪和如何異動資料...,等等,string是immutable所以不能異動!

取出資料

可以取出list中的某一個資料(字元的概念)和部分資料(子字串的概念),分別為indexesliced

...

...

...

慢著!這段根本就是從Day3-List-操作 複製貼上的阿!

哈哈,沒錯,不過仔細想想這也是python這門語言厲害的地方吧,將同一套抽象操作運用在不同的資料型態。

demo = "https://ithelp.ithome.com.tw"
print( "demo data:{}".format(demo) )

# demo data:https://ithelp.ithome.com.tw


# indexed
print( "first data:{}".format(demo[0]) )
print( "last data:{}".format(demo[-1]) )

# first data:h
# last data:w


try:
    print(demo[28])
except IndexError as e:
    print( "Index Error: {0}, the last idx is: {1}".format(e, len(demo)-1) )

# Index Error: string index out of range, the last idx is: 27


try:
    print(demo["10"])
except TypeError as e:
    print( "Type Error: {0}".format(e) )

# Type Error: string indices must be integers


# sliced
s1 = demo[:]
print( "sliced 1:{}".format(s1) )

s2 = demo[2:]
print( "sliced 2:{}".format(s2) )

s3 = demo[2:5]
print( "sliced 3:{}".format(s3) )

s4 = demo[:5]
print( "sliced 4:{}".format(s4) )

s5 = demo[-3:]
print( "sliced 5:{}".format(s5) )

s6 = demo[::2]
print( "sliced 6:{}".format(s6) )

s7 = demo[1::2]
print( "sliced 7:{}".format(s7) )

# sliced 1:https://ithelp.ithome.com.tw
# sliced 2:tps://ithelp.ithome.com.tw
# sliced 3:tps
# sliced 4:https
# sliced 5:.tw
# sliced 6:hts/ihl.toecmt
# sliced 7:tp:/tepihm.o.w

走訪

# iteration
concate = ""
idx = 0
while idx < len(demo):  
    print(demo[idx])
    concate += demo[idx]
    idx += 1
print( "concate:{}".format(concate) )

# concate:https://ithelp.ithome.com.tw

其他

concatenate

使用+連結,但若為不同資料型態時,例如int,會發生甚麼事呢?

# concate with other type
try:
    result = 2
    demo2 = "1+1="
    concate2 = demo2 + result
    print( "concate2: {}".format(concate2) )
except TypeError as e:
    print( "Type Error: {0}".format(e) )
    concate2 = demo2 + str(result)
    print( "concate2: {}".format(concate2) )

# concate:https://ithelp.ithome.com.tw
# Type Error: must be str, not int
# concate2:1+1=2

count: 計算子字串出現次數

# count
chars = []
idx = 0
while idx < len(demo):
    if demo[idx] not in chars:
        print( "{} count number is {}".format(demo[idx], demo.count(demo[idx])) )
    chars.append(demo[idx])
    idx += 1

# h count number is 3
# t count number is 5
# p count number is 2
# s count number is 1
# : count number is 1
# / count number is 2
# i count number is 2
# e count number is 2
# l count number is 1
# . count number is 3
# o count number is 2
# m count number is 2
# c count number is 1
# w count number is 1

find: 尋找子字串

# find
ithome_idx = demo.find("ithome")
s8 = demo[ithome_idx:]
print( "sliced 8: {}".format(s8) )

# sliced 8:ithome.com.tw

splitlines, strip, split, replace

利用splitlines, strip, split, replace組合,簡單計算詞頻
source from 25 Hints You’re Working on a High Performing Team

# splitlines, strip, split, replace
# source from https://hackernoon.com/25-hints-youre-working-on-a-high-performing-team-c4d02f27dd3
section = """\
Here’s the personal checklist I came up with. Of course, it is always a journey.
You’re never done. As I point out in #1, my primary “signal” is a growth 
mindset and some awareness of what better might look like.
"""
section_words = []
lines = section.splitlines()
print( "lines: {}".format(lines) )
for line in lines:
    words = line.strip().split(" ")
    for word in words:
        if word.find(".") > 0:
            section_words.append(word.replace(".", ""))
        elif word.find(",") > 0:
            section_words.append(word.replace(",", ""))
        elif word.find("\"") > 0:
            section_words.append(word.replace("\"", ""))
        elif word.find("“") > 0:
            section_words.append(word.replace("“", ""))
        else:
            section_words.append(word)
print( "section_words: {}".format(section_words) )
for word in set(section_words):
    word_freq = section_words.count(word)
    print( "{}=>{}".format(word, word_freq) )
    
# lines: ['Here’s the personal checklist I came up with. Of course, it is always a journey.', 'You’re never done. As I point out in #1, my primary “signal” is a growth ', 'mindset and some awareness of what better might look like.']
# section_words: ['Here’s', 'the', 'personal', 'checklist', 'I', 'came', 'up', 'with', 'Of', 'course', 'it', 'is', 'always', 'a', 'journey', 'You’re', 'never', 'done', 'As', 'I', 'point', 'out', 'in', '#1', 'my', 'primary', '“signal”', 'is', 'a', 'growth', 'mindset', 'and', 'some', 'awareness', 'of', 'what', 'better', 'might', 'look', 'like']
# I=>2
# growth=>1
# better=>1
# in=>1
# my=>1
# You’re=>1
# some=>1
# it=>1
# with=>1
# #1=>1
# awareness=>1
# mindset=>1
# a=>2
# what=>1
# course=>1
# came=>1
# Of=>1
# of=>1
# As=>1
# the=>1
# journey=>1
# done=>1
# up=>1
# checklist=>1
# Here’s=>1
# like=>1
# personal=>1
# is=>2
# and=>1
# out=>1
# point=>1
# primary=>1
# look=>1
# always=>1
# never=>1
# “signal”=>1
# might=>1

參考


上一篇
Day6-String-宣告
下一篇
Day8-String-stringprefix
系列文
if len(learning.python) == 30:31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言