Python第三章-字符串
生活随笔
收集整理的這篇文章主要介紹了
Python第三章-字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第三章 ?字符串
3.1 基本字符串操作
Python的字符串和元組差不多,是不可以進行改變的,如果想改變值,可以嘗試list序列化之后在進行修改。
{
? ?website = 'http://www.Python.org';
? ?website = [-3:] = 'com';?
? ?上面操作違法。
}
3.2 字符串格式化:精簡版
字符串格式化使用字符串格式化操作符(這個名字還是很恰當的)即%來實現。
基本用法例子
1.
? >>> format = "Hello, %s. %s enough for ya?";
? >>> values = ('world' ,'Hot');
? >>> print (format % values);
? Hello, world. Hot enough for ya?
2.
? >>> format = "Pi with three decimals: %.3f";
? >>> from math import pi
? >>> print(format % pi)
? Pi with three decimals: 3.142
3.模板字符串
? <基本用法>
? >>> from string import Template;
? >>> s = Template('$x. glorious $x!');
? >>> s.substitute(x='slurm')
? 'slurm. glorious slurm!'
? <模板字符串如果和別的單詞一起,那么要{x}區分>
? >>> s = Template("It's ${x}tastic!")
? >>> s.substitute(x='slurm')
? "It's slurmtastic!"
? >>>
? <顯示美元字符用兩個$>
? >>> s=Template("Make $$ selling $x!");
? >>> s.substitute(x='slurm')
? 'Make $ selling slurm!'
?<除了關鍵字參數之外,還可以使用字典變量提供值/名稱對>
? >>> s = Template('A $thing must never $action.');
? >>> d = {}
? >>> d['thing'] = 'gentleman'
? >>> d['action'] = 'show his socks'
? >>> s.substitute(d)
? 'A gentleman must never show his socks.'
? <safe_substitute 在查找不到的時候不會報錯>
? >>> s = Template('A $x');
? >>> s.substitute(a='x') ? 這個會報錯,因為查找不到
? >>> s.safe_substitute(a='x') ?不會報錯,并且輸出下面值
? 'A $x'
3.3 字符串格式化:完整版
? 格式化操作符的右操作數可以是任何東西,如果是元組或者映射類型(如字典)那么字符串格式化講會有所不同。
?
注意:
? 如果轉換表達式一部分是元組,那么必須將它用括號括起來,以避免出錯。
? {
? ?Ok
? ?>>> '%s plus %s equals %s' % (1 ,1 ,2)
? ?'1 plus 1 equals 2'
? ?Error
? ?>>> '%s plus %s equals %s' % 1,1,2
? ?Traceback (most recent call last):
? ?File "<pyshell#27>", line 1, in <module>'%s plus %s equals %s' % 1,1,2
? ?TypeError: not enough arguments for format string
? ?>>>?
? }
基本轉換說明符-(以下描述循序至關重要(就是使用順序))
? ?(1)%字符:標記轉換說明符的開始。
? ?(2)轉換標志(可選): -表示左對齊;?
? ? ? ? ? ? ? ? ?+表示在轉換值之前要加上正負號
? ? ? ? ? ? ? ? ?“” 正數之前保留空格
? ? ? ? ? ? ? ? ? 0 ?0填充
? ?(3) 最小字段寬度(可選):轉換后的字符串至少應該具有該指定值的寬度。
? ?如果是*,則寬度會從值元組中讀取。
? ?(4)點(.) 后跟隨精度值(可選):如果轉換的是實數,精度值就表示出現在小數點后的位數。如果轉換的是字符串,那么該數字就表示最大字段寬度。如果是*,那么精度將會從元組中讀出。
? ?(5)轉換類型
? ? ? ? ? d,i 帶符號的十進制整數
? ? ? ? ? o ? 不帶符號的八進制
? ? ? ? ? u ? 不帶符號的十進制
? ? ? ? ? x,X 十六進制
? ? ? ? ? e,E ?科學計數法
? ? ? ? ? f,F ?十進制浮點型
? ? ? ? ? g,G
? ? ? ? ? C ? ? 單字符
? ? ? ? ? r ? ? 字符串(使用repr轉換任意Python對象)
? ? ? ? ? s ? ? 字符串(使用str轉換任意Ptthon對象)
3.3.1簡單轉換
? ?>>> 'Price of eggs: $%d' %42
? ?'Price of eggs: $42'
? ?>>> 'Price of eggs: $%d' %42
? ?'Price of eggs: $42'
? ?>>> 'Hexadecimal price of eggs:%x' %42
? ?'Hexadecimal price of eggs:2a'
? ?>>> from math import pi
? ?>>> 'Pi: %f...' %pi
? ?'Pi: 3.141593...'
? ?>>> 'Very inexact estimate of pi: %i' %pi
? ?'Very inexact estimate of pi: 3'
? ?>>> 'Using str: %s' % 42L ?
? ?SyntaxError: invalid syntax ? (我用的3.5 高版本里買沒有顯示L了)
? ?>>> 'Using str: %s' % 42
? ?'Using str: 42'
? ?>>> 'Using repr: %r' %42
? ?'Using repr: 42'
? ?>>>?
3.3.2 字段寬度和精度
' ? ? ?3.14'
? ?>>> '%.2f' %pi
? ? '3.14'
? ? >>> '%.2s' %pi
? ? '3.'
? ? >>> '%.5s' % 'Guido van Rossum'
? ? 'Guido'
? ? <長度可以用*代替,然后在元組里給出>
? ? >>> '%.*s' %(5,'Guido van Rossum')
? ? 'Guido'
3.3.3 符號,對齊和0填充
? ? ?<0填充>
? ?>>> '%010.2f' %pi
'0000003.14'
? ?<左對齊>
>>> '%-10.2f' %pi
? ?'3.14 ? ? ?'
? ? ?<空格填充>
? ? ? ? >>> print(('% 5d' %10) + '\n' + ('% 5d' % -10))
? ? ? ? 10
? ? ? ? -10
?
? ? ?<正負號>
? ?>>> print(('%+5d' %10) + '\n' + ('%+5d' % -10))
? ?+10
? ?-10 ?
3.4 字符串方法
? 字符串常量
? {
? ??string.digits ?0~9
? ??string.letters 所有字母 大小寫
? ??string.lowercase 所有小寫字母
? ??string.printable 所有課打印的字符的字符串
? ??string.punctuation 包含所有標點的字符串
? ??string.uppercase ? 所有大寫字母的字符串
? ?} ?
? ??字符串常量(例如string.letters)與地區有區別,其本身取決于Python所配置的語言,如果可以確定自己使用的是ASCII那么就可以例如這樣 string.ascii_letters
3.4.1 find (找到輸出最左邊,找不到輸出-1)
>>> mark = "123456789123456789"
>>> mark.find("123456")
0
>>> mark.find("aasd")
-1
可接受區間定義 ? [)
{
>>> subject = "$$$ Get rich now!!! $$$"
>>> subject.find("$$$")
0
>>> subject.find("$$$" ,1)
20
>>> subject.find("!!!" ,0 ,16)
-1
}
3.4.2 join ?非常重要的字符串方法,它是split方法的逆方法,用來在隊列中添加元素
{
? ?>>> seq = [1,2,3,4,5]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
?File "<pyshell#2>", line 1, in <module>
sep.join(seq)
TypeError: sequence item 0: expected str instance, int found
>>> seq = ['1' ,'2' ,'3' ,'4' ,'5']
>>> sep.join(seq)
'1+2+3+4+5'
>>> sep
'+'
>>> seq
['1', '2', '3', '4', '5']
>>> dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print ('C:' + '\\'.join(dirs))
C:\usr\bin\env
>>>?
}
3.4.3 lower ?(title 所有首字母大寫,其他小寫)
? ? ?lower方法返回字符串的小寫字母版
? ? ?{
>>> 'asdaADdasdwDsdw'.lower()
'asdaaddasdwdsdw'
>>> name = 'Gumby'
>>> names = ['gumby' ,'smith' ,'jones']
>>> if name.lower() in names : print ('Fount it!')
Fount it!
>>>
? ? ? }
3.4.4 replace替換
{
? >>> "This is a test".replace('is','eez')
? 'Theez eez a test'
}
3.4.5 ?split(jion的逆方法,用來將字符串分割成序列)。
? ? {
>>> '1+2+3+4+5+6'.split('+')
['1', '2', '3', '4', '5', '6']
>>> '/use/dasd/w/ad/we'.split('/')
['', 'use', 'dasd', 'w', 'ad', 'we']
<如果不提供分割符,會把所有空格作為分隔符>
>>> "using the default ".split()
['using', 'the', 'default']
}
3.4.6 strip 去除字符串兩邊的空格(也可以指定去除字符)
{
>>> ' ?asdasd ? '.strip()
'asdasd'
>>> '000asd000asd00012'.strip('012')
'asd000asd'
} ?
3.4.7 translate ?這3.5已經取消了,這個先不看了。
3.1 基本字符串操作
Python的字符串和元組差不多,是不可以進行改變的,如果想改變值,可以嘗試list序列化之后在進行修改。
{
? ?website = 'http://www.Python.org';
? ?website = [-3:] = 'com';?
? ?上面操作違法。
}
3.2 字符串格式化:精簡版
字符串格式化使用字符串格式化操作符(這個名字還是很恰當的)即%來實現。
基本用法例子
1.
? >>> format = "Hello, %s. %s enough for ya?";
? >>> values = ('world' ,'Hot');
? >>> print (format % values);
? Hello, world. Hot enough for ya?
2.
? >>> format = "Pi with three decimals: %.3f";
? >>> from math import pi
? >>> print(format % pi)
? Pi with three decimals: 3.142
3.模板字符串
? <基本用法>
? >>> from string import Template;
? >>> s = Template('$x. glorious $x!');
? >>> s.substitute(x='slurm')
? 'slurm. glorious slurm!'
? <模板字符串如果和別的單詞一起,那么要{x}區分>
? >>> s = Template("It's ${x}tastic!")
? >>> s.substitute(x='slurm')
? "It's slurmtastic!"
? >>>
? <顯示美元字符用兩個$>
? >>> s=Template("Make $$ selling $x!");
? >>> s.substitute(x='slurm')
? 'Make $ selling slurm!'
?<除了關鍵字參數之外,還可以使用字典變量提供值/名稱對>
? >>> s = Template('A $thing must never $action.');
? >>> d = {}
? >>> d['thing'] = 'gentleman'
? >>> d['action'] = 'show his socks'
? >>> s.substitute(d)
? 'A gentleman must never show his socks.'
? <safe_substitute 在查找不到的時候不會報錯>
? >>> s = Template('A $x');
? >>> s.substitute(a='x') ? 這個會報錯,因為查找不到
? >>> s.safe_substitute(a='x') ?不會報錯,并且輸出下面值
? 'A $x'
3.3 字符串格式化:完整版
? 格式化操作符的右操作數可以是任何東西,如果是元組或者映射類型(如字典)那么字符串格式化講會有所不同。
?
注意:
? 如果轉換表達式一部分是元組,那么必須將它用括號括起來,以避免出錯。
? {
? ?Ok
? ?>>> '%s plus %s equals %s' % (1 ,1 ,2)
? ?'1 plus 1 equals 2'
? ?Error
? ?>>> '%s plus %s equals %s' % 1,1,2
? ?Traceback (most recent call last):
? ?File "<pyshell#27>", line 1, in <module>'%s plus %s equals %s' % 1,1,2
? ?TypeError: not enough arguments for format string
? ?>>>?
? }
基本轉換說明符-(以下描述循序至關重要(就是使用順序))
? ?(1)%字符:標記轉換說明符的開始。
? ?(2)轉換標志(可選): -表示左對齊;?
? ? ? ? ? ? ? ? ?+表示在轉換值之前要加上正負號
? ? ? ? ? ? ? ? ?“” 正數之前保留空格
? ? ? ? ? ? ? ? ? 0 ?0填充
? ?(3) 最小字段寬度(可選):轉換后的字符串至少應該具有該指定值的寬度。
? ?如果是*,則寬度會從值元組中讀取。
? ?(4)點(.) 后跟隨精度值(可選):如果轉換的是實數,精度值就表示出現在小數點后的位數。如果轉換的是字符串,那么該數字就表示最大字段寬度。如果是*,那么精度將會從元組中讀出。
? ?(5)轉換類型
? ? ? ? ? d,i 帶符號的十進制整數
? ? ? ? ? o ? 不帶符號的八進制
? ? ? ? ? u ? 不帶符號的十進制
? ? ? ? ? x,X 十六進制
? ? ? ? ? e,E ?科學計數法
? ? ? ? ? f,F ?十進制浮點型
? ? ? ? ? g,G
? ? ? ? ? C ? ? 單字符
? ? ? ? ? r ? ? 字符串(使用repr轉換任意Python對象)
? ? ? ? ? s ? ? 字符串(使用str轉換任意Ptthon對象)
3.3.1簡單轉換
? ?>>> 'Price of eggs: $%d' %42
? ?'Price of eggs: $42'
? ?>>> 'Price of eggs: $%d' %42
? ?'Price of eggs: $42'
? ?>>> 'Hexadecimal price of eggs:%x' %42
? ?'Hexadecimal price of eggs:2a'
? ?>>> from math import pi
? ?>>> 'Pi: %f...' %pi
? ?'Pi: 3.141593...'
? ?>>> 'Very inexact estimate of pi: %i' %pi
? ?'Very inexact estimate of pi: 3'
? ?>>> 'Using str: %s' % 42L ?
? ?SyntaxError: invalid syntax ? (我用的3.5 高版本里買沒有顯示L了)
? ?>>> 'Using str: %s' % 42
? ?'Using str: 42'
? ?>>> 'Using repr: %r' %42
? ?'Using repr: 42'
? ?>>>?
3.3.2 字段寬度和精度
? ?>>> '%10f' %pi' ?
? ? ? 3.141593'
? ?>>> '%10.2f' %pi' ? ? ?3.14'
? ?>>> '%.2f' %pi
? ? '3.14'
? ? >>> '%.2s' %pi
? ? '3.'
? ? >>> '%.5s' % 'Guido van Rossum'
? ? 'Guido'
? ? <長度可以用*代替,然后在元組里給出>
? ? >>> '%.*s' %(5,'Guido van Rossum')
? ? 'Guido'
3.3.3 符號,對齊和0填充
? ? ?<0填充>
? ?>>> '%010.2f' %pi
'0000003.14'
? ?<左對齊>
>>> '%-10.2f' %pi
? ?'3.14 ? ? ?'
? ? ?<空格填充>
? ? ? ? >>> print(('% 5d' %10) + '\n' + ('% 5d' % -10))
? ? ? ? 10
? ? ? ? -10
?
? ? ?<正負號>
? ?>>> print(('%+5d' %10) + '\n' + ('%+5d' % -10))
? ?+10
? ?-10 ?
3.4 字符串方法
? 字符串常量
? {
? ??string.digits ?0~9
? ??string.letters 所有字母 大小寫
? ??string.lowercase 所有小寫字母
? ??string.printable 所有課打印的字符的字符串
? ??string.punctuation 包含所有標點的字符串
? ??string.uppercase ? 所有大寫字母的字符串
? ?} ?
? ??字符串常量(例如string.letters)與地區有區別,其本身取決于Python所配置的語言,如果可以確定自己使用的是ASCII那么就可以例如這樣 string.ascii_letters
3.4.1 find (找到輸出最左邊,找不到輸出-1)
>>> mark = "123456789123456789"
>>> mark.find("123456")
0
>>> mark.find("aasd")
-1
可接受區間定義 ? [)
{
>>> subject = "$$$ Get rich now!!! $$$"
>>> subject.find("$$$")
0
>>> subject.find("$$$" ,1)
20
>>> subject.find("!!!" ,0 ,16)
-1
}
3.4.2 join ?非常重要的字符串方法,它是split方法的逆方法,用來在隊列中添加元素
{
? ?>>> seq = [1,2,3,4,5]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
?File "<pyshell#2>", line 1, in <module>
sep.join(seq)
TypeError: sequence item 0: expected str instance, int found
>>> seq = ['1' ,'2' ,'3' ,'4' ,'5']
>>> sep.join(seq)
'1+2+3+4+5'
>>> sep
'+'
>>> seq
['1', '2', '3', '4', '5']
>>> dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print ('C:' + '\\'.join(dirs))
C:\usr\bin\env
>>>?
}
3.4.3 lower ?(title 所有首字母大寫,其他小寫)
? ? ?lower方法返回字符串的小寫字母版
? ? ?{
>>> 'asdaADdasdwDsdw'.lower()
'asdaaddasdwdsdw'
>>> name = 'Gumby'
>>> names = ['gumby' ,'smith' ,'jones']
>>> if name.lower() in names : print ('Fount it!')
Fount it!
>>>
? ? ? }
3.4.4 replace替換
{
? >>> "This is a test".replace('is','eez')
? 'Theez eez a test'
}
3.4.5 ?split(jion的逆方法,用來將字符串分割成序列)。
? ? {
>>> '1+2+3+4+5+6'.split('+')
['1', '2', '3', '4', '5', '6']
>>> '/use/dasd/w/ad/we'.split('/')
['', 'use', 'dasd', 'w', 'ad', 'we']
<如果不提供分割符,會把所有空格作為分隔符>
>>> "using the default ".split()
['using', 'the', 'default']
}
3.4.6 strip 去除字符串兩邊的空格(也可以指定去除字符)
{
>>> ' ?asdasd ? '.strip()
'asdasd'
>>> '000asd000asd00012'.strip('012')
'asd000asd'
} ?
3.4.7 translate ?這3.5已經取消了,這個先不看了。
總結
以上是生活随笔為你收集整理的Python第三章-字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 第二章-列表和元组
- 下一篇: Python第四章-字典