[轉載] Python-Strings

參考鏈接: 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.

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540507.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540507.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540507.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

aes-128算法加密_加密算法問題-人工智能中的一種約束滿意問題

aes-128算法加密The Crypt-Arithmetic problem in Artificial Intelligence is a type of encryption problem in which the written message in an alphabetical form which is easily readable and understandable is converted into a numeric form which is neither easily…

讀書筆記《集體智慧編程》Chapter 2 : Make Recommendations

本章概要本章主要介紹了兩種協同過濾(Collaborative Filtering)算法,用于個性化推薦:基于用戶的協同過濾(User-Based Collaborative Filtering,又稱 K-Nearest Neighbor Collaborative Filtering&#xff0…

[轉載] python中的for循環對象和循環退出

參考鏈接: Python中循環 流程控制-if條件 判斷條件,1位true,0是flesh,成立時true,不成立flesh,not取反 if 1; print hello python print true not取反,匹配取反,表示取非1…

設計一個應用程序,以在C#中的按鈕單擊事件上在MessageBox中顯示TextBox中的文本...

Here, we took two controls on windows form that are TextBox and Button, named txtInput and btnShow respectively. We have to write C# code to display TextBox’s text in the MessageBox on Button Click. 在這里,我們在Windows窗體上使用了兩個控件&…

Oracle優化器:星型轉換(Star Query Transformation )

Oracle優化器:星型轉換(Star Query Transformation )Star query是一個事實表(fact table)和一些維度表(dimension)的join。每個維度表都跟事實表通過主外鍵join,且每個維度表之間不j…

[轉載] python循環中break、continue 、exit() 、pass的區別

參考鏈接: Python中的循環和控制語句(continue, break and pass) 1、break:跳出循環,不再執行 用在while和for循環中 用來終止循環語句,即循環條件沒有False條件或者序列還沒被完全遞歸完,也會停止執行循環語句 如果…

JavaScript | 聲明數組并使用數組索引分配元素的代碼

Declare an array, assign elements by indexes and print all elements in JavaScript. 聲明一個數組&#xff0c;通過索引分配元素&#xff0c;并打印JavaScript中的所有元素。 Code: 碼&#xff1a; <html><head><script>var fruits [];fruits[0]"…

[轉載] Python入門(輸入/輸出、數據類型、條件/循環語句)

參考鏈接&#xff1a; Python中的循環技術 在介紹之前我們先來看看計算機的三個根本性基礎&#xff1a; 1.計算機是執行輸入、運算、輸出的機器 2.程序是指令和數據的集合 3.計算機的處理方式有時與人們的思維習慣不同 &#xff08;以上是引自《計算機是怎樣跑起來的》…

第5章 函數與函數式編程

第5章 函數與函數式編程 凡此變數中函彼變數者&#xff0c;則此為彼之函數。 ( 李善蘭《代數學》) 函數式編程語言最重要的基礎是λ演算&#xff08;lambda calculus&#xff09;&#xff0c;而且λ演算的函數可以傳入函數參數&#xff0c;也可以返回一個函數。函數式編程 (簡稱…

mcq 隊列_人工智能能力問答中的人工智能概率推理(MCQ)

mcq 隊列1) Which of the following correctly defines the use of probabilistic reasoning in AI systems? In situations of uncertainty, probabilistic theory can help us give an estimate of how much an event is likely to occur or happen.It helps to find the pr…

[轉載] Python中的xrange和range的區別

參考鏈接&#xff1a; Python中的range()和xrange() 在python2 中 range(start,end,step)返回一個列表&#xff0c;返回的結果是可迭代對象&#xff0c;但不是迭代器。iter()轉化為列表迭代器。xrange()返回的是一個序列&#xff0c;他也是可迭代對象&#xff0c;但不是迭代…

Kubernetes基礎組件概述

本文講的是Kubernetes基礎組件概述【編者的話】最近總有同學問Kubernetes中的各個組件的相關問題&#xff0c;其實這些概念內容在官方文檔中都有&#xff0c;奈何我們有些同學可能英文不好&#xff0c;又或者懶得去看&#xff0c;又或者沒有找到&#xff0c;今天有時間就專門寫…

c語言將鏈表寫入二進制文件_通過逐級遍歷將二進制樹轉換為單鏈表的C程序

c語言將鏈表寫入二進制文件Problem statement: Write a C program to convert a binary tree into a single linked list by traversing level-wise. 問題陳述&#xff1a;編寫一個C程序&#xff0c;通過逐級遍歷將二進制樹轉換為單個鏈表 。 Example: 例&#xff1a; The ab…

[轉載] C Primer Plus 第6章 C控制語句 6.16 編程練習及答案

參考鏈接&#xff1a; 用Python打印金字塔圖案的程序 2019獨角獸企業重金招聘Python工程師標準>>> 1、編寫一個程序&#xff0c;創建一個具有26個元素的數組&#xff0c;并在其中存儲26個小寫字母。并讓該程序顯示該數組的內容。 #include int main (void) { …

C# String和string的區別

C#中同時存在String與string MSDN中對string的說明&#xff1a; string is an alias for String in the .NET Framework。string是String的別名而已&#xff0c;string是c#中的類&#xff0c;String是Framework的類&#xff0c;C# string 映射為 Framework的 String。如果用str…

要求用戶在Python中輸入整數| 限制用戶僅輸入整數值

input() function can be used for the input, but it reads the value as a string, then we can use the int() function to convert string value to an integer. input()函數可用于輸入&#xff0c;但它將值讀取為字符串&#xff0c;然后可以使用int()函數將字符串值轉換為…

[轉載] python——if語句、邏輯運算符號

參考鏈接&#xff1a; 用Python鏈接比較運算符 1.if條件判斷語句&#xff1a; if 要判斷的條件(True): 條件成立的時候&#xff0c;要做的事情 elif 要判斷的條件(True): .... elif 要判斷的條件(True): .... else: 條件不成立的時候要做的事情 示例&#xff1a; 判斷學生…

洛谷 P2689 東南西北【模擬/搜索】

題目描述 給出起點和終點的坐標及接下來T個時刻的風向(東南西北)&#xff0c;每次可以選擇順風偏移1個單位或者停在原地。求到達終點的最少時間。 如果無法偏移至終點&#xff0c;輸出“-1”。 輸入輸出格式 輸入格式&#xff1a; 第一行兩個正整數x1,y1&#xff0c;表示小明所…

單鏈表遍歷_單鏈表及其遍歷實現的基本操作

單鏈表遍歷單鏈表 (Single linked list) Single linked list contains a number of nodes where each node has a data field and a pointer to next node. The link of the last node is to NULL, indicates end of list. 單個鏈表包含許多節點&#xff0c;其中每個節點都有一…

[轉載] python中for語句用法_詳解Python中for循環的使用_python

參考鏈接&#xff1a; 在Python中將else條件語句與for循環一起使用 這篇文章主要介紹了Python中for循環的使用,來自于IBM官方網站技術文檔,需要的朋友可以參考下 for 循環 本系列前面 “探索 Python&#xff0c;第 5 部分&#xff1a;用 Python 編程” 一文討論了 if 語句和…