


Detailed explanation of Character string in Python with examples
Sep 26, 2017 am 10:40 AMThe following editor will bring you an article on Character string in python (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look
1. Python string
String is the most commonly used data type in Python. We can use quotation marks (' or ") to create strings. l
Python does not support single character types, and single characters are also used as a string in Python.
>>> var1 = 'hello python' #定義字符串 >>> print(var1[0]) #切片截取,從0開始,不包括截取尾數(shù) h >>> print(var1[0:5]) hello >>> print(var1[-6:]) python >>> var2 = var1[0:6]+'world' #截取字符并拼接賦值給新變量 >>> print(var2) hello world
2. Python escape character
\ : At the end of the line, it is the line continuation character
\\ : Backslash escape, output '\'
\' :Single quote escape
\":Double quote escape
\b :Backspace
\n :Line feed
\v :Vertical tab character
\t :Horizontal tab character
\r :Carriage return
\f :Page change
3. python string operators
(+) splicing, (*) repetition, ( []) index, ([:]) slicing, (in) member judgment, (not in) non-member judgment, (r/R) element output string
>>> var1 = 'hello' >>> var2 = 'python' >>> print(var1+var2) #拼接字符串 hellopython >>> print(var1*3) #重復(fù)輸出字符串 hellohellohello >>> print(var1[0]) #索引字符串 h >>> print(var1[3:]) #索引切片 lo >>> 'e' in var1 #判斷字符串是否在變量中 True >>> 'p' not in var1 #判斷字符串是否不在變量中 True >>> print("he\tllo \n") he llo >>> print(r"he\tllo \n") #原始輸出字符串,也就是原始輸出轉(zhuǎn)義字符 he\tllo \n
4. Formatted strings
Python supports the output of formatted strings. Although this can lead to very complex expressions, the most basic usage is to insert a value into a string with the string formatting character %s.
In Python, string formatting uses the same syntax as the sprintf function in C.
Python string formatting symbols:
%c | Formatting characters and their ASCII codes |
%s | Format string |
%d | Format integer |
%u | Format unsigned integer |
%o | Format unsigned octal number |
%x | Format unsigned hexadecimal number |
%X | Format unsigned hexadecimal number System number (uppercase) |
%f | Format floating point numbers, you can specify the precision after the decimal point |
%e | Use scientific notation to format floating point numbers |
%E | The function is the same as %e, use scientific notation to format floating point numbers |
%g | Abbreviation of %f and %e |
%G | Abbreviation of %f and %E |
%p | Format the address of a variable as a hexadecimal number |
Format operator Auxiliary instructions:
* | Define width or decimal point precision |
- | Used for left alignment |
+ | Display plus sign (+) in front of positive numbers |
Display spaces before positive numbers | |
#Display zero ('0') before octal numbers, and before hexadecimal numbers Display '0x' or '0X' (depending on whether 'x' or 'X' is used) | |
0 | The displayed number is filled with '0' in front and Instead of the default space |
% | '%%' outputs a single '%' |
(var) | Map variable (dictionary parameter) |
m.n. | m is the minimum total width of the display, n is the number of digits after the decimal point (if available) |
##
>>> print("ascii:%c"%'s') #格式化輸出字符 ascii:s >>> print("ascii:%c"%'1') #格式化輸出數(shù)字 ascii:1 >>> print("str:%s"%'character string') #格式化字符串 str:character string >>> print("str:%d"%888) #格式化整數(shù) str:888 >>> print("str:%f"%888) #格式浮點(diǎn)數(shù) str:888.000000 >>> print("str:%e"%888) #格式化科學(xué)計(jì)數(shù)浮點(diǎn)數(shù) str:8.880000e+02 >>> print("str:%E"%888) #同上 str:8.880000E+02 >>> print("str:%G"%888) #%f和%E的簡(jiǎn)寫 str:888 >>> print("str:%20f"%888.089) #定義20寬度輸出 str: 888.089000 >>> print("str:%-20f"%888.089) #用左對(duì)齊 str:888.089000 >>> print("str:%+20f"%888.089) #在正數(shù)前顯示加號(hào) str: +888.089000 >>> print("str:%+-20f"%888.089) #左對(duì)齊顯示加號(hào) str:+888.089000 >>> print("str:%020f"%888.089) #以0填充默認(rèn)的空格 str:0000000000888.089000 >>> print("str:%%%20f"%888.089) #在數(shù)字前輸入%號(hào) str:% 888.089000 >>> print("str:%%%-20f"%888.089) #左對(duì)齊輸出%號(hào) str:%888.089000 >>> print("str:%20.3f"%888.089) #顯示最小總寬度20,小數(shù)點(diǎn)后位數(shù)為3位 str: 888.089Since python2.6, the format string function str.format():usage has been added : It uses {} and : to replace % Positional parameters are not subject to order constraints, and can be {} empty, as long as there is a corresponding parameter value in the format. If the parameter value is not enough, an error will be reported. The parameter index starts from 0, and the incoming positional parameter list can be *list
In [27]: '{}+{}={}'.format(1,2,3) #格式化按順序應(yīng)用參數(shù)值 Out[27]: '1+2=3' In [28]: '{2}-{1}={0}'.format(1,2,3) #指定順序應(yīng)用參數(shù)值 Out[28]: '3-2=1' In [29]: '{0}+{0}={1}'.format(2,3) #指定參數(shù)可以重復(fù)使用 Out[29]: '2+2=3' In [30]: '{}+{}={}'.format(2,3) #如不指定順序,format參數(shù)不夠就會(huì)報(bào)錯(cuò) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-30-29f40e412920> in <module>() ----> 1 '{}+{}={}'.format(2,3) IndexError: tuple index out of range In [31]: l1 = [2,4,8] In [32]: '{}*{}={}'.format(*l1) #使用列表引用參數(shù)值 Out[32]: '2*4=8' In [33]: dct = {'name':'python','age':20} #定義字典 In [35]: 'welcom to {name},age is {age}'.format(name='qi',age=28) #變量引用 Out[35]: 'welcom to qi,age is 28' In [36]: 'welcom to {name},age is {age}'.format(**dct) #使用**引用字典參數(shù)必須填寫key值 Out[36]: 'welcom to python,age is 20' 填充與格式化: In [53]: "{0: >20}".format("string") #從0位開始已空格填充20寬度左對(duì)齊 Out[53]: ' string' In [54]: "{0:&>20}".format("string") Out[54]: '&&&&&&&&&&&&&&string' In [55]: "{0:#>20}".format("string") #使用#號(hào)會(huì)有個(gè)小bug ....: Out[55]: '##############string' In [60]: '{0:+<20}'.format("string") #向右對(duì)齊填充+ Out[60]: 'string++++++++++++++' In [61]: '{0:+^20}'.format("string") #劇中對(duì)齊填充+ Out[61]: '+++++++string+++++++' 精度與進(jìn)制: >>> '{0:.3f}'.format(10/3) #小數(shù)位進(jìn)度格式化 '3.333' >>> '{0:b}'.format(8) #格式化二進(jìn)制 '1000' >>> '{0:o}'.format(9) #格式化八進(jìn)制 '11' >>> '{0:x}'.format(26) #格式化十六進(jìn)制 '1a' >>> '{0:,}'.format(123456789) #千分位格式化 '123,456,789' 使用索引: >>> l2 = ['AA',{'bb':'cc'},('d','e')] #列表索引引用 >>> 'outing:{0[0]}'.format(l2) 'outing:AA' >>> 'outing:{0[0]},{0[1]}'.format(l2) #將列表當(dāng)成一個(gè)元素,在其中索引值 "outing:AA,{'bb': 'cc'}"
5. Python's string method
>>> s = 'i mi to' #將字符串的第一個(gè)字符改為大寫 >>> s.capitalize() 'I mi to' >>> s = 'I MI TO' #將字符串所有字符改為小寫 >>> s.casefold() 'i mi to' >>> s.center(15) #將字符串劇中,并用空格將字符串填充長(zhǎng)度,如指定長(zhǎng)度小于實(shí)際長(zhǎng)度則沒有效果 ' I MI TO ' >>> s = 'abcabcabcabc' #返回sub在字符串里出現(xiàn)的次數(shù),start,end為可選參數(shù),決定范圍 >>> s.count('a',0,12) 4 >>> s.encode(encoding='utf-8',errors='strict') #以encoding指定的編碼格式對(duì)字符串進(jìn)行編碼 b'abcabcabcabc' >>> s.endswith('abc',1,12) #檢查字符串是否以sub結(jié)尾,是返回True,否返回False,start,end為可選參數(shù),決定范圍 True >>> s = 'a\tb\tc' >>> s.expandtabs(4) #把字符串的tab字符(\t)轉(zhuǎn)化為空格,如不指定tabsize,默認(rèn)為8個(gè)空格 'a b c' >>> s.find('b') #檢測(cè)字符串是否在字符串中,如在則返回索引,否則返回-1,可指定起始值。 2 >>> s='hello python' >>> s.index('hello') # 類似find(),不同在于如果sub不在字符串中,返回異常 0 >>> s.isalnum() #有空格返回false False >>> s='hellopython' >>> s.isalnum() #如果字符串至少有一個(gè)字符,并且所有字符都是字母或數(shù)字則返回True,否則False True >>> s.isalpha() #如果字符串至少有一個(gè)字符,并且所有字符都是字母則返回True,否則False True >>> s = '123' >>> s.isdigit() #如果字符串只包含數(shù)字則返回True,否則返回False True >>> s = '123' >>> s.isdecimal() #如果字符串只包含十進(jìn)制數(shù)字則返回True,否則返回False True >>> s= 'ox123' >>> s.isdecimal() False >>> s = '0.33' >>> s.isdecimal() False >>> s = 'abc' >>> s.islower() #如果字符中至少包含一個(gè)能區(qū)分大小寫的字符,并且這些字符都是小寫則返回True,否則返回Flase True >>> s = 'Abc' >>> s.islower() False >>> s = 'ABC' >>> s.isupper() #果字符中至少包含一個(gè)能區(qū)分大小寫的字符,并且這些字符都是大寫則返回True,否則返回Flase True >>> s = 'ABc' >>> s.isupper() False >>> >>> s = '123' >>> s.isnumeric() #如果字符串只包含數(shù)字字符,則返回True,否則返回False True >>> s = '123a' >>> s.isnumeric() False >>> 'def'.isidentifier() #判斷字符串是否包含該語言的保留字 True >>> 'aaa'.isprintable() #判斷是否可以打印 True >>> ''.isspace() False >>> ' '.isspace() #判斷字符串中至少有一個(gè)字符且所有都是空格,否則返回false True >>> ' a'.isspace() False >>> 'Abc'.istitle() #判斷是否是標(biāo)題 格式,可以理解為首字母大寫。 True >>> 'aBC'.istitle() False >>> s = '123' >>> '_'.join(s) #返回一個(gè)用指定字符串分隔的字,或者是將指定字符加入到另一個(gè)字符中。 '1_2_3' >>> s.join('abc') 'a123b123c' >>> s = 'ABC' >>> s.lower() #返回的是指定字符串的拷貝,并轉(zhuǎn)化成小寫 'abc' >>> s.ljust(10,'+') #可以指定寬度,以及填充字符串,返回的是按寬度,填充字符串格式化后的左對(duì)齊的字符串。 'ABC+++++++' >>> 'aaabccc'.partition('b') #在字符串中查找指定的字符,如找到則返回字符前部分,字符本身和后部分,如沒找到則返回字符串和兩個(gè)空字符串。 ('aaa', 'b', 'ccc') >>> 'aaabccc'.partition('e') ('aaabccc', '', '') >>> 'aaabccc'.rpartition('b') #與partition一樣,但是是從右邊開始 ('aaa', 'b', 'ccc') >>> 'aaabccc'.rpartition('c') ('aaabcc', 'c', '') >>> 'aaaaabbcc'.replace('a','A') #用指定字符串替換指定字符串,如果不指定替換次數(shù),則替換所有 'AAAAAbbcc' >>> 'aaaaabbcc'.replace('a','A',2) 'AAaaabbcc' >>> 'aabbcc'.rfind('a') #返回指定子串的最高索引,如果沒找到則返回-1,可以指定要開始替換的起始,結(jié)束位置。 1 >>> 'aabbcc'.rfind('e') -1 >>> 'aabbcc'.rindex('a') #與上面的rfind一樣,只是如果沒找到不是返回-1,而是觸發(fā)錯(cuò)誤 1 >>> 'aabbcc'.rindex('e') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> 'aa'.rjust(10,'+') #與ljust()相對(duì)應(yīng),右對(duì)齊 '++++++++aa' >>> 'aa'.ljust(10,'+') 'aa++++++++' >>> 'aabccbddbee'.split('b') ##按指定字符串對(duì)目標(biāo)字符串進(jìn)行切割,可以指定切割次數(shù) ['aa', 'cc', 'dd', 'ee'] >>> 'aabccbddbee'.split('b',2) ['aa', 'cc', 'ddbee'] >>> 'aabccbddbee'.rsplit('b',2) #與split作用相同,但是從右側(cè)開始 ['aabcc', 'dd', 'ee'] >>> ' aabb '.strip() #移除字符串兩側(cè)的指定字符串,默認(rèn)移除空格,需要注意的是可以指定多個(gè)字符 'aabb' >>> ' aabb'.strip('b') ' aa' >>> ' aabb'.strip('ab') ' ' >>> 'beaacebb'.rstrip('eb') #與strip一樣,從右側(cè)刪除指定字符,可以為多個(gè) 'beaac' >>> 'aa\nbb\ncc\ndd'.splitlines() #按換行符切割顯示,如沒指定keepends=True則將換行符移除。 ['aa', 'bb', 'cc', 'dd'] >>> 'aa\nbb\ncc\ndd'.splitlines(keepends=True) ['aa\n', 'bb\n', 'cc\n', 'dd'] >>> 'aabbc'.startswith('a') #判斷字符串是否以某個(gè)字符開頭,可以是多字符 True >>> 'aabbc'.startswith('b') False >>> 'aabbc'.startswith('aab') True >>> 'aaBBcc'.swapcase() #轉(zhuǎn)換大小寫 'AAbbCC' >>> 'wend is ok'.title() #標(biāo)題格式,首字母大寫,其它字符小寫 'Wend Is Ok' >>> 'wend is ok'.upper() #將字符全部轉(zhuǎn)換成大寫 'WEND IS OK' >>> 'wend is ok'.zfill(20) #這里的z指zero,用0將字符填充到指定長(zhǎng)度 '0000000000wend is ok'
The above is the detailed content of Detailed explanation of Character string in Python with examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

pandas.melt() is used to convert wide format data into long format. The answer is to define new column names by specifying id_vars retain the identification column, value_vars select the column to be melted, var_name and value_name, 1.id_vars='Name' means that the Name column remains unchanged, 2.value_vars=['Math','English','Science'] specifies the column to be melted, 3.var_name='Subject' sets the new column name of the original column name, 4.value_name='Score' sets the new column name of the original value, and finally generates three columns including Name, Subject and Score.

First, define a ContactForm form containing name, mailbox and message fields; 2. In the view, the form submission is processed by judging the POST request, and after verification is passed, cleaned_data is obtained and the response is returned, otherwise the empty form will be rendered; 3. In the template, use {{form.as_p}} to render the field and add {%csrf_token%} to prevent CSRF attacks; 4. Configure URL routing to point /contact/ to the contact_view view; use ModelForm to directly associate the model to achieve data storage. DjangoForms implements integrated processing of data verification, HTML rendering and error prompts, which is suitable for rapid development of safe form functions.

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

Introduction to Statistical Arbitrage Statistical Arbitrage is a trading method that captures price mismatch in the financial market based on mathematical models. Its core philosophy stems from mean regression, that is, asset prices may deviate from long-term trends in the short term, but will eventually return to their historical average. Traders use statistical methods to analyze the correlation between assets and look for portfolios that usually change synchronously. When the price relationship of these assets is abnormally deviated, arbitrage opportunities arise. In the cryptocurrency market, statistical arbitrage is particularly prevalent, mainly due to the inefficiency and drastic fluctuations of the market itself. Unlike traditional financial markets, cryptocurrencies operate around the clock and their prices are highly susceptible to breaking news, social media sentiment and technology upgrades. This constant price fluctuation frequently creates pricing bias and provides arbitrageurs with

iter() is used to obtain the iterator object, and next() is used to obtain the next element; 1. Use iterator() to convert iterable objects such as lists into iterators; 2. Call next() to obtain elements one by one, and trigger StopIteration exception when the elements are exhausted; 3. Use next(iterator, default) to avoid exceptions; 4. Custom iterators need to implement the __iter__() and __next__() methods to control iteration logic; using default values is a common way to safe traversal, and the entire mechanism is concise and practical.
