日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python正确的字符串常量_4.1 字符串常量(python)

發(fā)布時(shí)間:2023/12/15 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python正确的字符串常量_4.1 字符串常量(python) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

《Python Linux系統(tǒng)管理與自動(dòng)化運(yùn)維》學(xué)習(xí)之路:

1、字符串介紹

定義字符串,單引號,雙引號

轉(zhuǎn)義字符,反斜杠‘\’

原始字符串,‘r’,抑制轉(zhuǎn)義

字符串較長較負(fù)責(zé),可使用三引號定義,‘‘‘ ‘‘‘或""" """,三引號內(nèi)的引號,換行符,制表符等特殊字符,都被認(rèn)為是普通字符,多行字符串也不受代碼塊縮進(jìn)規(guī)則限制,因?yàn)樗旧砭筒皇谴a,而是普通字符串。

兩個(gè)相連的字符串會自動(dòng)組成一個(gè)新的字符串:

In [1]: s = ‘hello‘ ‘world‘

In [3]: s

Out[3]: ‘helloworld‘

字符串不可變,是字符的有序組合

下標(biāo)訪問,分片操作

列表反序 s[::-1]

內(nèi)置函數(shù)reversed(seq)

使用reversed()返回一個(gè)迭代器,需要使用循環(huán)來訪問

In [5]: s

Out[5]: ‘hello,world‘

In [8]: ‘‘.join(reversed(s))

Out[8]: ‘dlrow,olleh‘

In [15]: for i in reversed(s):

....: print(i)

....:

d

l

r

o

w

,

o

l

l

e

h

a.sort()是對列表a進(jìn)行原地修改,而且只能修改列表

sorted(a)對字符串、列表、元組都能排序,該函數(shù)返回一個(gè)排序好的列表

2、字符串函數(shù)

通用操作

獲取字符串長度 len(x)

判斷元素是否存在于集合中: ‘x‘ in s

都可應(yīng)用于元組,列表等有序集合中

與大小寫有關(guān)的方法:

upper 將字符串轉(zhuǎn)換為大寫

lower 將字符串轉(zhuǎn)換為小寫

isupper 判斷字符串是否都為大寫

islower 判斷字符串是否都為小寫

swapcase 將字符串中的大寫轉(zhuǎn)小寫,小寫轉(zhuǎn)大寫

capitalize 將首字母轉(zhuǎn)大寫

istitle 判斷字符串是不是一個(gè)標(biāo)題

判斷類方法

s.isalpha 只包含字母,非空

s.isalnum 只包含字母和數(shù)字,非空

s.isspace 包含空格、制表符、換行符、非空

s.isdecimal 只包含數(shù)字,非空

字符串方法

判斷參數(shù)是否為字符串的前綴或后綴

startwith

endswith

實(shí)例:

[item for item in os.listdir(‘.‘) if item.startswith(‘index‘)]

In [28]: index = [item for item in os.listdir(‘.‘) if item.startswith(‘index‘)]

In [29]: size = [os.path.getsize(os.path.join(‘/root‘, item)) for item in index]

In [30]: print(size)

[20810, 20810, 2381, 20810, 20810, 20810, 20810, 2381, 20810]

查找類函數(shù)

find 查找字串在字符串中的位置,查找失敗,返回-1

index 與find類似,查找失敗,拋出ValueError異常

rfind 與find類似,區(qū)別在于從后查找

rindex 與index類似,區(qū)別在于從后查找

實(shí)例:

In [31]: s = ‘Return the lower index in S where substring sub is found‘

In [32]: s.find(‘in‘)

Out[32]: 17

可以指定查找范圍,如從下標(biāo)18開始:

In [33]: s.find(‘in‘, 18)

Out[33]: 23

In [34]: s.find(‘not exist‘)

Out[34]: -1

判斷一個(gè)字符串是另一個(gè)字符串的字串,正確應(yīng)使用in和not in

字符串操作方法

join 接受任何可迭代的對象,不止列表

實(shí)例:

In [38]: with open(‘/etc/passwd‘) as fd:

....: print(‘###‘.join(fd))

....:

root:x:0:0:root:/root:/bin/bash

###bin:x:1:1:bin:/bin:/sbin/nologin

###daemon:x:2:2:daemon:/sbin:/sbin/nologin

###adm:x:3:4:adm:/var/adm:/sbin/nologin

字符串拼接:

>>> print(‘root‘, ‘/root‘, 100, sep=‘:‘)

root:/root:100

# 適合python3

拆分函數(shù)split(),默認(rèn)是空白字符(空格。換行符,制表符)進(jìn)行拆分

裁剪函數(shù) strip(), rstrip(), lstrip()

實(shí)例:

In [4]: s = ‘root:x:0:0:root:/root:/bin/bash‘

In [5]: s.split(‘:‘)

Out[5]: [‘root‘, ‘x‘, ‘0‘, ‘0‘, ‘root‘, ‘/root‘, ‘/bin/bash‘]

In [7]: s = ‘a(chǎn) b c d‘

In [8]: s.split()

Out[8]: [‘a(chǎn)‘, ‘b‘, ‘c‘, ‘d‘]

In [9]: s = ‘ \thello, \tworld \n‘

In [12]: s.strip()

Out[12]: ‘hello, \tworld‘

In [13]: s.rstrip()

Out[13]: ‘ \thello, \tworld‘

In [14]: s.lstrip()

Out[14]: ‘hello, \tworld \n

可以給strip函數(shù)傳入?yún)?shù),參數(shù)是需要裁剪的字符集和,字符串的順序不重要,重復(fù)字符沒有任何效果

In [15]: s = ‘##hello, world##‘

In [16]: s.strip(‘#‘)

Out[16]: ‘hello, world‘

In [17]: s.strip(‘###‘)

Out[17]: ‘hello, world‘

In [18]: s.strip(‘h#d‘)

Out[18]: ‘ello, worl‘

In [19]: s.strip(‘dh#‘)

Out[19]: ‘ello, worl‘

3、實(shí)例

使用python分析Apache的訪問日志

(1)統(tǒng)計(jì)PV,UV

#!/usr/bin/python

#-*- coding: UTF-8 -*-

from __future__ import print_function

ips = []

with open(‘a(chǎn)ccess.log‘) as f:

for line in f:

ips.append(line.split()[0])

print(‘PV is {0}‘.format(len(ips)))

print(‘UV is {0}‘.format(len(set(ips))))

(2 )統(tǒng)計(jì)熱門資源

使用collections.Couter,使用方法與字典類似,對于普通的計(jì)數(shù)功能,比字典更加好用

In [26]: from collections import Counter

In [27]: c = Counter(‘a(chǎn)bcba‘)

In [28]: c

Out[28]: Counter({‘a(chǎn)‘: 2, ‘b‘: 2, ‘c‘: 1})

In [29]: c[‘a(chǎn)‘] += 1

In [30]: c

Out[30]: Counter({‘a(chǎn)‘: 3, ‘b‘: 2, ‘c‘: 1})

In [31]: c[‘a(chǎn)‘] += 1

In [32]: c

Out[32]: Counter({‘a(chǎn)‘: 4, ‘b‘: 2, ‘c‘: 1})

In [33]: c

Out[33]: Counter({‘a(chǎn)‘: 4, ‘b‘: 2, ‘c‘: 1})

In [34]: c.most_common(2)

Out[34]: [(‘a(chǎn)‘, 4), (‘b‘, 2)]

In [35]: c[‘d‘] += 1

In [36]: c

Out[36]: Counter({‘a(chǎn)‘: 4, ‘b‘: 2, ‘c‘: 1, ‘d‘: 1})

In [37]: c.most_common(3)

Out[37]: [(‘a(chǎn)‘, 4), (‘b‘, 2), (‘c‘, 1)]

如果一個(gè)鍵不存在計(jì)數(shù)器中,直接對這個(gè)鍵操作運(yùn)算也不會報(bào)錯(cuò),會添加進(jìn)去

most_common 顯示Counter中取值最大的幾個(gè)元素

#!/usr/bin/python

#-*- coding: UTF-8 -*-

from __future__ import print_function

from collections import Counter

c = Counter()

with open(‘a(chǎn)ccess.log‘) as f:

for line in f:

c[line.split()[6]] += 1

print(‘Popular resources : {0}‘.format(c.most_common(10)))

(3)分析錯(cuò)誤請求數(shù)

#!/usr/bin/python

#-*- coding: UTF-8 -*-

from __future__ import print_function

d = {}

with open(‘a(chǎn)ccess.log‘) as f:

for line in f:

key = line.split()[8]

d.setdefault(key, 0)

d[key] += 1

sum_requests = 0

error_requests = 0

for key, val in d.iteritems():

if int(key) >=400:

error_requests += val

sum_requests += val

print(error_requests, sum_requests)

print(‘error rate : {0:.2f}%‘.format(error_requests * 100.0 / sum_requests))

4、字符串格式化 format

(1)占位符或下標(biāo)形式訪問

In [6]: ‘{} is apple‘.format(‘a(chǎn)pple‘)

Out[6]: ‘a(chǎn)pple is apple‘

In [7]: ‘{0} is apple‘.format(‘a(chǎn)pple‘)

Out[7]: ‘a(chǎn)pple is apple‘

(2)關(guān)鍵字參數(shù)形式訪問

In [2]: dic1 = {‘a(chǎn)‘:1, ‘b‘:2, ‘c‘:3}

In [5]: ‘{a} is 1, {b} is 2, {c} is 3, {a} little {c}‘.format(**dic1)

Out[5]: ‘1 is 1, 2 is 2, 3 is 3, 1 little 3‘

(3)可直接訪問對象的屬性

(4)format功能

精度:

In [8]: ‘{:.2f}‘.format(3.1415926)

Out[8]: ‘3.14‘

顯示正數(shù)符合:

In [9]: ‘{:+.2f}‘.format(3.1415926)

Out[9]: ‘+3.14‘

寬度:

In [10]: ‘{:10.2f}‘.format(3.1415926)

Out[10]: ‘ 3.14‘

對其方式:

In [11]: ‘{:^10.2f}‘.format(3.1415926)

Out[11]: ‘ 3.14 ‘

填充符號:

In [12]: ‘{:_^10.2f}‘.format(3.1415926)

Out[12]: ‘___3.14___‘

千位分隔符:

In [13]: ‘{:,}‘.format(31415926)

Out[13]: ‘31,415,926‘

綜合顯示:

In [14]: ‘{:_^+20,.2f}‘.format(31415926)

Out[14]: ‘___+31,415,926.00___‘

原文地址:http://www.cnblogs.com/yshan13/p/7804299.html

總結(jié)

以上是生活随笔為你收集整理的python正确的字符串常量_4.1 字符串常量(python)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。