"python的字串教學"

星期三 10 Apr 2019   even  
教學

前言

文字,很多文字,你每天都要接觸文字、處理文字、閱讀文字,這是我們不可避免的宿命,然而,你有想過使用程式碼自動幫你處理文字嗎?只要學會了python的基本文字處理,重複性、無聊的文字處理作業,就可以被完全取代掉。在處理很多很多亂七八糟的檔案時,不論是檔案目錄、檔案名稱、檔案內容,最簡便的方式就是當成文字來處理。而python具有程式界赫赫有名的強大文字處理能力,直觀、簡潔、易操作!也因此只要好好學會本章節的內容,保證能夠省下你寶貴的生命,可以花在更加有意義的事情上面~

總之,我們開始這段教學吧~

' 字串就是由字元構成的 "list" '

由兩個單引號或雙引號構成的內容就是字串,也是一種類別的物件,有著屬於字串才有的方法以及運算方式。

基本上,python的字串,就是以字元所組成的list,因此很多基本的操作和list一模一樣,可使用字元的index直接進行字串的切割,也可使用len()來確認有幾個字元,如以下程式碼:

A = 'PUF STUDIO超棒'
print(type(A)) # 為str類別的物件
print(len(A)) # A有幾個字元? 空白或特殊符號都算喔

print(A)
print(A[:-2]) # 字串的切割和list的操作方式一模一樣
print(A[::-1]) # 字串倒過來
print(A[2::2]) # 從第二個字到尾,每隔兩個

<class 'str'>
12
PUF STUDIO超棒
PUF STUDIO
棒超OIDUTS FUP
FSUI超

字串的運算符號 + * in 的使用也與list一模一樣唷:

A = 'PUF STUDIO'
B = '好棒'
C = '棒'
print(A + B * 4 + C)

print('好棒棒' in A + B * 4 + C)

PUF STUDIO好棒好棒好棒好棒棒
True

Bonus Tip

1. 如果你需要多行的字串,可以使用兩個'''或"""來區隔出一段區間,這裡面多行的內容就會變成你的字串,要多長就可以有多長。

2. 兩個單引號或雙引號的用法是可以讓字串裡面使用另一種引號,而不會和外面的引號衝突。

如下:

poem = '''
白 日 依 山 盡,黃 河 入 海 流 。
欲 窮 千 里 目,更 上 一 層 樓 。
'''
print(len(poem))
print(poem)

a = '123"4"56' #兩種引號的使用
b = "654'3'21"

45

白 日 依 山 盡,黃 河 入 海 流 。
欲 窮 千 里 目,更 上 一 層 樓 。

字串的方法

字串有一大堆方法,我就只介紹我會使用到的幾個,如果沒有包含你想要的功能的話,請自行看說明文檔。當想要知道這個類別的物件有什麼方法時,可以輸入help(類別名稱),即可顯示說明文檔,從中查找符合你需求的方法。

如下:

help(str)

Help on class str in module builtins:

class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Use keyword.iskeyword() to test for reserved identifiers such as "def" and
| "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the words in the string, using sep as the delimiter string.
|
| sep
| The delimiter according which to split the string.
| None (the default value) means split according to any whitespace,
| and discard empty strings from the result.
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| Splits are done starting at the end of the string and working to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the words in the string, using sep as the delimiter string.
|
| sep
| The delimiter according which to split the string.
| None (the default value) means split according to any whitespace,
| and discard empty strings from the result.
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace remove.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| maketrans(x, y=None, z=None, /)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.

你可以看到裡面有一大堆的方法,提供你處理你的字串,但是有許多許多的方法是針對英文所設計,如:

方法 說明 範例 結果
str.lower() 將大寫的字母轉成小寫 'Puf Studio is so good.'.lower() 'puf studio is so good.'
str.upper() 將小寫的字母轉成大寫 'Puf Studio is so good.'.upper() 'PUF STUDIO IS SO GOOD.'
str.title() 轉成標題(首字母大寫) 'Puf Studio is so good.'.title() 'Puf Studio Is So Good.'
str.islower() 是否全為小寫? 'puf studio is so good.'.islower() True
str.isupper() 是否全為大寫? 'Puf Studio is so good.'.isupper() False
str.istitle() 是否全為標題? 'Puf Studio Is So Good.'.istitle() True

上面這些很明顯的,只有有區分大小寫的語言適用,如果用在中文字上則不會有任何作用。

除此之外,常用的方法還有:

方法 說明 範例 結果
str.startswith(s) 是否以s字串開頭? 'Puf Studio is so good.'.startswith('Puf') True
str.endswith(s) 是否以s字串結尾? 'Puf Studio is so good.'.endswith('good.') True
str.replace(s1,s2) 將裡面s1字串以s2取代 'Puf Studio is so good.'.replace(' ', '***') 'Puf***Studio***is***so***good.'
str.split(s) 用字串s為基準分割成list 'Puf Studio is so good.'.split(' ') ['Puf', 'Studio', 'is', 'so', 'good.']
str.center(i,c) 在字串前後補上c字元,讓長度等於i 'PUF'.center(15, '*') '******PUF******'

以上簡單介紹比較常用的幾個字串的方法,事實上,我最常用的也只有str.split和str.replace而已。這兩個方法加上字串切割,以及接下來要介紹的格式化字串,這已經逐以應付大多數的問題了。

格式化字串

字串可以和字串很簡單的就由 + 來串接在一起,但是,當你想要和非字串類的物件(如:整數)接在一起時,你就必須先轉成字串。如下:

print('我今年' + str(7) + '歲半') # 使用str()將整數7轉成字串'7'
print('我今年' + 7 + '歲半') # 整數跟字串無法相加,因此報錯

我今年7歲半
Traceback (most recent call last):

File "<ipython-input-115-06923a93d841>", line 2, in <module>
print('我今年' + 7 + '歲半') # 整數跟字串無法相加,因此報錯

TypeError: can only concatenate str (not "int") to str

每次都要把非字串類別的物件轉成文字實在很麻煩,有沒有簡便的方式呢?有的! 那就是這裡要介紹的格式化字串。

python的格式化字串使用方式一再演變,從一開始較不直觀的用法,到現在最簡便的方式,就我所知道的共有三種用法,鼓勵大家都用最新的方式。

如下:

year = 7

# string format method 1 (old)
'我今年%s歲半'%(year)

# string format method 2 (new)
'我今年{}歲半'.format(year)
'我今年{i}歲半'.format(i = year)

# string format method 3 (latest)
f'我今年{year}歲半'

我只針對上面最新的方式深入介紹,在字串的開頭加上f代表這是要進行格式化的字串,裡面使用{},在其中放入你想插入的變數即可,可以使用任意數量的{},非常直觀且方便,如下:

year = 2019
month = 4
day = 11
print(f'今天是西元{year}年{month}月{day}號')

今天是西元2019年4月11號

Bonus Tip: 如何將字串轉成python的程式並執行?

經常在處理字串的時候會看到'15/36'這種字串,有沒有什麼快速的方法直接去獲得15/36的數值呢?有的!可以使用eval,會直接將字串轉成python的程式碼,並且運行,使用上雖然很方便,但是一定要注意安全性的問題喔!

使用方式如下:

a = 'print([15, 12'
b = ',6,7 ][0])'
print(a+b)
eval(a+b)
num = eval('15/36')
print(num)

print([15, 12,6,7 ][0])
15
0.4166666666666667

結語

以上就是關於字串的基本使用方式,這樣我們就已經學會python最基本的類型囉~

(等等,還有字典沒教...之後再補吧...)

只要熟悉這些基本的類型的操作方式,再加上接下來要介紹的迴圈、if、自訂函數等,我們就可以寫出一些很不錯的程式囉!!

總之,感謝您耐心閱讀到這裡,希望你有學到些什麼,祝你有美好的一天,我們下段教學見啦~Bye~

python新手教學
Why python
Hello Python!
This is a python - 基本數值運算與邏輯判斷
[Python, 的, list, 教學 ]
"python的字串教學"
python的迴圈與流程控制
python的(tuple)與{dict}
def 一個python的自訂函數:
import套件到你的python
python的嘗試try與錯誤error處理
Python之禪

相關文章:

>