String Method2

join() and split()

split()是一個相當常用的方法,就是將字串依照一個分割字符串分割成一個一個的子字串, 這些子字串會以list的形式儲存起來。

join()則是split()的相反,將字串串列依照一個連接字符串,一個一個的將串列中的子字串連接起來。

我們來看看以下的範例:

paragraph = '''
This is first line.
This is second line.
And the last line.
'''

splitLines = paragraph.split('.')
print(splitLines)

joinedStr = '.'.join(splitLines)
print(joinedStr)

我們可以看到,跑這個程式時,會印出split之後,與join之後的結果,可以發現join()split()的逆向操作。

rjust(), ljust(), center()

這三個方法是以某個字串為添補字串將字串對齊,說起來有點繞口,我們來試看看就知道。

hello = 'Hello World~'

print(hello.ljust(20, '*'))
print(hello.rjust(20, '*'))
print(hello.center(20, '*'))

"""
印出來的結果為:
Hello World~********
********Hello World~
****Hello World~****
"""

可以知道,''就是一個填補字元,我們希望將hello這個變數,以''為填補字元,填補成字串長度為20,必且同時對齊, 而ljust就是向左對齊,rjust就是向右對齊,center就是置中對齊, 想用什麼填補字元都可以。

strip(), rstrip(), lstrip()

這三個是將空白鍵或是指定字元修剪掉的方法,strip()是將字串從左右同時修剪,rstrip()是從右修剪,lstrip()是從左修剪。

我們來看看以下的範例:

hello = '      This is Jason\'s notebook.   '
print(hello.strip())
print(hello.lstrip())
print(hello.rstrip())

print(hello.strip('Tko. '))
print(hello.lstrip('Tko. '))
print(hello.rstrip('Tko. '))

不帶有引數的strip(),是將空白鍵或等空白字串修剪掉,帶有引數的則將所給的字元修剪掉, 例如此例為'T', 'k', 'o', '.', ' ',這五個字元。

Last updated

Was this helpful?