參考鏈接: Python成員資格和身份運算符 | in, not in, is, is not
Strings?
?
介紹?
String是Python中最常用的類型。僅僅用引號括起字符就可以創建string變量。字符串使用單引號或雙引號對Python來說是一樣的。?
var1 = 'Hello World!'
var2 = "Python Programming"?
訪問string的值?
Python不支持單字符類型,那些長度為1的字符串因為被認為是子字符串。為了獲取子字符串,可以通過索引的方式,例?
var1 = 'Hello World!'
var2 = "Python Programming"
print("var1[0]: ", var1[0])
print("var2[1:5]: ", var2[1:5])?
執行結果?
var1[0]:? H
var2[1:5]:? ytho?
更新Strings?
可以通過重新分配的方式更新一個字符串,新的字符串可以跟原來的相關或與不同的字符串組合,例?
var1 = 'Hello World!'
print("Updated String :- ", var1[:6] + 'Python')?
執行結果?
Updated String :-? Hello Python?
轉義字符?
下表是可以使用反斜杠()表示的轉義字符或不可以打印字符?
反斜杠表示十六進制字符描述\a0x07Bell or alert\b0x08Backspace\cxControl-x\C-xControl-x\e0x1bEscape\f0x0cFormfeed\M-\C-xMeta-Control-x\n0x0aNewline\nnnOctal notation, where n is in the range 0.7\r0x0dCarriage return\s0x20Space\t0x09Tab\v0x0bVertical tab\xCharacter x\xnnHexadecimal notation, where n is in the range 0.9, a.f, or A.F
String特殊操作符?
假設字符串變量a表示’Hello’, 字符串b表示’Python",因此?
操作符描述示例+結合 - 在運算符的任意一側添加值a + b 表示HelloPython*重復 - 創建一個新的字符串,是原字符串的多次拷貝a*2 表示 HelloHello[]切片 - 表示指定索引的字符a[1] 表示 e[:]范圍切片 - 表示指定范圍的字符a[1:4] 表示 ellin成員資格 - 如果字符在指定的字符串中返回True‘H’ in a 表示Truenot in成員資格 - 如果字符不在指定的字符串中返回True‘M’ not in a 表示Truer或R原始字符串 - 放在字符串前,告訴編譯器輸出元素字符,不要轉義,r或R都可以打開文件的路徑:r"Directory"%格式化 - 格式化字符串建議使用Format語句
三個雙引號?
Python的三個雙引號允許字符串跨越多行,可包含特殊字符,打印出其效果。?
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print(para_str)?
執行結果?
this is a long string that is made up of
several lines and non-printable characters such as
TAB (? ?) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [?
?], or just a NEWLINE within
the variable assignment will also show up.?
Unicode字符串?
通常字符串在Python中以8位ASCII碼存儲,而Unicode字符串以16位的統一碼存儲。這樣就允許更多樣化的字符,包括世界上大多數的語言特殊字符。?
print(u'Hello, world!')?
執行結果?
Hello, world!?
String內置方法?
Sr.No.方法描述1capitalize() Capitalizes first letter of string2center(width, fillchar) Returns a space-padded string with the original string centered to a total of width columns3count(str, start= 0,end=len(string)) Counts how many times str occurs in string or in a substring of string if starting index start and ending index end are given.4decode(encoding=‘UTF-8’,errors=‘strict’) Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.5encode(encoding=‘UTF-8’,errors=‘strict’) Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.6endswith(suffix, beg=0, end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.7expandtabs(tabsize=8) Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.8find(str, beg=0 end=len(string)) Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.9index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found.10isalnum() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.11isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.12isdigit() Returns true if string contains only digits and false otherwise.13islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.14isnumeric() Returns true if a unicode string contains only numeric characters and false otherwise15isspace() Returns true if string contains only whitespace characters and false otherwise.16istitle() Returns true if string is properly “titlecased” and false otherwise.17isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.18join(seq) Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.19len(string) Returns the length of the string20ljust(width[, fillchar]) Returns a space-padded string with the original string left-justified to a total of width columns.21lower() Converts all uppercase letters in string to lowercase22lstrip() Removes all leading whitespace in string.23maketrans() Returns a translation table to be used in translate function24max(str) Returns the max alphabetical character from the string str.25min(str) Returns the min alphabetical character from the string str26replace(old, new [, max]) Replaces all occurrences of old in string with new or at most max occurrences if max given.27rfind(str, beg=0,end=len(string)) Same as find(), but search backwards in string.28rindex( str, beg=0, end=len(string)) Same as index(), but search backwards in string29rjust(width,[, fillchar]) Returns a space-padded string with the original string right-justified to a total of width columns.30rstrip() Removes all trailing whitespace of string.31split(str="", num=string.count(str)) Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given32splitlines( num=string.count(’\n’)) Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.33startswith(str, beg=0,end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.34strip([chars]) Performs both lstrip() and rstrip() on string.35swapcase() Inverts case for all letters in string.36title() Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.37translate(table, deletechars="") Translates string according to translation table str(256 chars), removing those in the del string.38upper() Converts lowercase letters in string to uppercase.39zfill (width) Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).40isdecimal() Returns true if a unicode string contains only decimal characters and false otherwise.