Python字符串練習題


python—字符串的拼接、去重、反轉、字母花樣排序、單詞出現判斷、統計文件單詞頻率、硬盤容量、列表轉字符串

  1. 已知字符串 a = “aAsmr3idd4bgs7Dlsf9eAF”,要求如下 
    1.1 請將a字符串的大寫改為小寫,小寫改為大寫。
#使用字符串的內置方法a.swapcase():
>>> a = 'aAsmr3idd4bgs7Dlsf9eAF'
>>> a
'aAsmr3idd4bgs7Dlsf9eAF'
>>> print a.swapcase()
AaSMR3IDD4BGS7dLSF9Eaf
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

1.2 請將a字符串的數字取出,並輸出成一個新的字符串。

#字符串有個內置判斷函數,如果字符是純數字返回True,否則返回False。
>>> a = '2345'
>>> a
'2345'
>>> a.isdigit()
True
>>> b = 'we34234'
>>> b.isdigit()
False
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
>>> a = 'aAsmr3idd4bgs7Dlsf9eAF'
>>> a
'aAsmr3idd4bgs7Dlsf9eAF'
>>> print [s for s in a if s.isdigit()]
['3', '4', '7', '9']
>>> print ''.join([s for s in a if s.isdigit()])
3479
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
''.join([s for s in a if s.isdigit()])
表達的意思為:
列表l = []
for s in a:#遍歷a字符串里面所有字符
    if s.isdigit():
        l.append(s)
''.join() 把所有數字去除任何字符進行組裝起來
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

讀取一個Log1.txt中的所有數字,並拼接在一起

#系統測試log1.txt文件
root@kali:~/python/laowangpy# cat log1.txt 
2017-09-18:xuweibo login in pmsweb at 3:10:45 pm
2017-09-18:xuweibo del admin235 in pmsweb at 4:23:59 pm
2017-09-19:xuweibo mod xwb21 in pmsweb at 6:18:34 pm
2017-09-19:xuweibo login out pmsweb at 19:01:34 pm
root@kali:~/python/laowangpy# 

#腳本執行文件:
root@kali:~/python/laowangpy# ls
log1.txt  tokenno.py
root@kali:~/python/laowangpy# cat tokenno.py 
#!/usr/bin/python
# --*-- coding:utf-8 --*--

f1 = open('log1.txt','r')
str = ''.join([n for n in f1.read(1000)])
print str
print ''.join([x for x in str if x.isdigit()])
f1.close()

root@kali:~/python/laowangpy# 

#腳本執行情況:
root@kali:~/python/laowangpy# python tokenno.py
2017-09-18:xuweibo login in pmsweb at 3:10:45 pm
2017-09-18:xuweibo del admin235 in pmsweb at 4:23:59 pm
2017-09-19:xuweibo mod xwb21 in pmsweb at 6:18:34 pm
2017-09-19:xuweibo login out pmsweb at 19:01:34 pm

2017091831045201709182354235920170919216183420170919190134
root@kali:~/python/laowangpy# 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

1.3 請統計a字符串出現的每個字母的出現次數(忽略大小寫,a與A是同一個字母),並輸出成一個字典。 例 {‘a’:4,’b’:2}

#內置方法統計次數
>>> c = 'aasdebbcaa'
>>> c.count('a')
4
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5
>>> a
'aAsmr3idd4bgs7Dlsf9eAF'
>>> a = a.lower()#所有字母都小寫
>>> a
'aasmr3idd4bgs7dlsf9eaf'
>>> print [(x,a.count(x)) for x in set(a)]#首先把a的所有字符串一個一個的拆成列表形式,並遍歷每個字符串,且計算每個字符串出現次數。
[('a', 3), ('b', 1), ('e', 1), ('d', 3), ('g', 1), ('f', 2), ('i', 1), ('m', 1), ('3', 1), ('l', 1), ('s', 3), ('r', 1), ('4', 1), ('7', 1), ('9', 1)]
>>> print dict([(x,a.count(x)) for x in set(a)])#把計算出的列表轉化成字典形式
{'a': 3, 'b': 1, 'e': 1, 'd': 3, 'g': 1, 'f': 2, 'i': 1, 's': 3, 'm': 1, 'l': 1, '3': 1, 'r': 1, '4': 1, '7': 1, '9': 1}
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

1.4 請去除a字符串多次出現的字母,僅留最先出現的一個。例 ‘abcabb’,經過去除后,輸出 ‘abc’

root@kali:~/python/laowangpy# cat sortzimu.py 
#!/usr/bin/python
# --*-- coding:utf-8 --*--

a = 'aAsmr3idd4bugs7Dlsf9eAF'
print "----原始字符串----"
print a

a_list = list(a)
print "----轉換列表----"
print a_list

set_list = list(set(a_list))
print '-----去重列表字符串后,變成新的列表-----'
print set_list

set_list.sort(key=a_list.index)
print "----拼接原先位置字符串並去重后組成新的字符串------"
print ''.join(set_list)

#a_list = list(a)#轉換成list列表
#set_list = list(set(a_list))#對列表內容去重,然后再轉換回list。set表示去重
#set_list.sort(key=a_list.index)#對去重以后的list進行原先的排序
#print ''.join(set_list)#拼接成字符串
root@kali:~/python/laowangpy# 
root@kali:~/python/laowangpy# python sortzimu.py
----原始字符串----
aAsmr3idd4bugs7Dlsf9eAF
----轉換列表----
['a', 'A', 's', 'm', 'r', '3', 'i', 'd', 'd', '4', 'b', 'u', 'g', 's', '7', 'D', 'l', 's', 'f', '9', 'e', 'A', 'F']
-----去重列表字符串后,變成新的列表-----
['a', 'A', 'b', 'e', 'd', 'g', 'f', 'i', 'F', 'm', '3', 'l', 's', 'r', 'u', '4', '7', '9', 'D']
----拼接原先位置字符串並去重后組成新的字符串------
aAsmr3id4bug7Dlf9eF
root@kali:~/python/laowangpy# 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

1.5 請將a字符串反轉並輸出。例:’abc’的反轉是’cba’ 
第一種方式:

>>> a
'aAsmr3idd4bugs7Dlsf9eAF'
>>> print a[::-1]#存在步長為-1說明該字符串為倒敘輸出排序的
FAe9fslD7sgub4ddi3rmsAa
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5

第二種方式:

>>> a = 'aAsmr3idd4bugs7Dlsf9eAF'
>>> a
'aAsmr3idd4bugs7Dlsf9eAF'
>>> alist = list(a)
>>> alist
['a', 'A', 's', 'm', 'r', '3', 'i', 'd', 'd', '4', 'b', 'u', 'g', 's', '7', 'D', 'l', 's', 'f', '9', 'e', 'A', 'F']
>>> alist.reverse()
>>> alist
['F', 'A', 'e', '9', 'f', 's', 'l', 'D', '7', 's', 'g', 'u', 'b', '4', 'd', 'd', 'i', '3', 'r', 'm', 's', 'A', 'a']
>>> print ''.join(alist)
FAe9fslD7sgub4ddi3rmsAa
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

1.6 去除a字符串內的數字后,請將該字符串里的單詞重新排序(a-z),並且重新輸出一個排序后的字符 串。(保留大小寫,a與A的順序關系為:A在a前面。例:AaBb)

#偽代碼
1、要有小寫字母從a-z的排序
2、大小寫不同,但值相同的字母,大寫在小寫前面

#腳本如下:
root@kali:~/python/laowangpy# vi sortzimu2.py
root@kali:~/python/laowangpy# python sortzimu2.py
['3', '4', '7', '9', 'A', 'A', 'D', 'F', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'i', 'l', 'm', 'r', 's', 's', 's']
root@kali:~/python/laowangpy# vi sortzimu2.py
root@kali:~/python/laowangpy# cat sortzimu2.py 
#!/usr/bin/python
# --*-- coding:utf-8 --*--

''' #偽代碼 1、要有小寫字母從a-z的排序 2、大小寫不同,但值相同的字母,大寫在小寫前面 '''

a = 'aAsmr3idd4bgs7Dlsf9eAF'

l = sorted(a)#該方法意思是把數字0-9從小到大排序,再對大寫字母A-Z從小到大排序,然后對小寫字母a-z從小到大排序
print l

root@kali:~/python/laowangpy# 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
root@kali:~/python/laowangpy# 
root@kali:~/python/laowangpy# cat sortzimu2.py 
#!/usr/bin/python
# --*-- coding:utf-8 --*--

''' #偽代碼 1、要有小寫字母從a-z的排序 2、大小寫不同,但值相同的字母,大寫在小寫前面 '''

a = 'aAsmr3idd4bgs7Dlsf9eAF'

l = sorted(a)#該方法意思是把數字0-9從小到大排序,再對大寫字母A-Z從小到大排序,然后對小寫字母a-z從小到大排序
print l#運行后l的列表為['3', '4', '7', '9', 'A', 'A', 'D', 'F', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'i', 'l', 'm', 'r', 's', 's', 's']

a_upper_list = []#存放大寫字母列表
a_lower_list = []#存放小寫字母列表

for x in l:#遍歷列表l
    if x.isupper():#如果x元素是大寫字母則進入
        a_upper_list.append(x)
    elif x.islower():#如果x元素是大寫字母則進入
        a_lower_list.append(x)
    else:
        pass

for y in a_upper_list:#在大寫的列表中迭代,如果小寫列表中有大寫字母,則把大寫字母插入小寫字母前面
    y_lower = y.lower()
    print '---y_lower---'
    print y_lower
    if y_lower in a_lower_list:
        a_lower_list.insert(a_lower_list.index(y_lower),y)
        print '---a_lower_list----'
        print a_lower_list

print ''.join(a_lower_list)

root@kali:~/python/laowangpy# 
root@kali:~/python/laowangpy# 
root@kali:~/python/laowangpy# 
root@kali:~/python/laowangpy# python sortzimu2.py
['3', '4', '7', '9', 'A', 'A', 'D', 'F', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'i', 'l', 'm', 'r', 's', 's', 's']
---y_lower---
a
---a_lower_list----
['A', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'i', 'l', 'm', 'r', 's', 's', 's']
---y_lower---
a
---a_lower_list----
['A', 'A', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'i', 'l', 'm', 'r', 's', 's', 's']
---y_lower---
d
---a_lower_list----
['A', 'A', 'a', 'b', 'D', 'd', 'd', 'e', 'f', 'g', 'i', 'l', 'm', 'r', 's', 's', 's']
---y_lower---
f
---a_lower_list----
['A', 'A', 'a', 'b', 'D', 'd', 'd', 'e', 'F', 'f', 'g', 'i', 'l', 'm', 'r', 's', 's', 's']
AAabDddeFfgilmrsss
root@kali:~/python/laowangpy# 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

1.7 請判斷 ‘boy’里出現的每一個字母,是否都出現在a字符串里。如果出現,則輸出True,否則,則輸 出False.

解題思路

root@kali:~/python/laowangpy# python
Python 2.7.3 (default, Mar 14 2014, 11:57:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1,2,3,4,5]
>>> d = set(a)#把a列表轉成集合d
>>> d
set([1, 2, 3, 4, 5])
>>> len(d)
5
>>> d
set([1, 2, 3, 4, 5])
>>> d.update([4])#對集合d更新元素,如果存在就不會更新元素,因此總長度不變,否則則變化總長度
>>> d
set([1, 2, 3, 4, 5])
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
root@kali:~/python/laowangpy# vi searchzimu.py
root@kali:~/python/laowangpy# cat searchzimu.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--

a = 'AaAsmr3idd4bgsboy7Dlsf9eAF'
search = 'boy'

u = set(a)
print u
u.update(list(search))#把要查找的字符串更新到a的列表中,如果存在相同順序的字符串的則返回true,否則返回False
print len(set(a)) == len(u)

root@kali:~/python/laowangpy# python searchzimu.py
set(['A', 'a', 'b', 'e', 'd', 'g', 'f', 'i', 'F', 'm', '3', 'o', 'l', '9', 's', 'r', '4', '7', 'y', 'D'])
True
root@kali:~/python/laowangpy# 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

1.8 要求如1.7,此時的單詞判斷,由’boy’改為四個,分別是 ‘boy’,’girl’,’bird’,’dirty’,請判斷如上這4個字符串里的每個字母,是否都出現在a字符串里。

root@kali:~/python/laowangpy# cat searchzimu2.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--

a = 'aAsrm3idd4boygs7Dlsf9eAF'


search = ['boy','girl','brird','dirty']

b = set(a)#把a列表變成集合
print b

for i in search:
    b.update(list(i))

print len(b) == len(set(a))

root@kali:~/python/laowangpy# python searchzimu2.py
set(['a', 'A', 'b', 'e', 'd', 'g', 'f', 'i', 'F', 'm', '3', 'o', 'l', '9', 's', 'r', '4', '7', 'y', 'D'])
False
root@kali:~/python/laowangpy# 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

1.9 輸出a字符串出現頻率最高的字母

root@kali:~/python/laowangpy# vi nocount.py
root@kali:~/python/laowangpy# cat nocount.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--

a = 'AaAsmr3idd4bgsboy7Dlsf9eAF'

l = ([(x,a.count(x)) for x in set(a)])#作為列表形式統計每個字符出現次數
print '------未排序的列表-------'
print l

l.sort(key = lambda k:k[1],reverse=True)#取出列表中每個元素的第二個鍵值,並使用從大到小的排序
print '-------字母出現的頻率從大到小排序的---------'
print l
print '-------第一個元素-------'
print l[0]
print '----第一個元素的第一個鍵值-----'
print l[0][0]

root@kali:~/python/laowangpy# python nocount.py
------未排序的列表-------
[('A', 3), ('a', 1), ('b', 2), ('e', 1), ('d', 2), ('g', 1), ('f', 1), ('i', 1), ('F', 1), ('m', 1), ('3', 1), ('o', 1), ('l', 1), ('9', 1), ('s', 3), ('r', 1), ('4', 1), ('7', 1), ('y', 1), ('D', 1)]
-------字母出現的頻率從大到小排序的---------
[('A', 3), ('s', 3), ('b', 2), ('d', 2), ('a', 1), ('e', 1), ('g', 1), ('f', 1), ('i', 1), ('F', 1), ('m', 1), ('3', 1), ('o', 1), ('l', 1), ('9', 1), ('r', 1), ('4', 1), ('7', 1), ('y', 1), ('D', 1)]
-------第一個元素-------
('A', 3)
----第一個元素的第一個鍵值-----
A
root@kali:~/python/laowangpy# 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

2.在python命令行里,輸入import this 以后出現的文檔,統計該文檔中,”be” “is” “than” 的出現次數。

root@kali:~/python/laowangpy# python -m this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
root@kali:~/python/laowangpy# 

root@kali:~/python/laowangpy# python -m this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!


root@kali:~/python/laowangpy# 
root@kali:~/python/laowangpy# vi beiscount.py
root@kali:~/python/laowangpy# cat beiscount.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--

import os
m = os.popen('python -m this').read()#使用os命令運行python -m this

m = m.replace('\n','')#對換行符進行替換

l = m.split(' ')#使用空格分割

print [(x,l.count(x)) for x in ['be','is','than']]#統計多個單詞在文件中出現頻率

root@kali:~/python/laowangpy# python beiscount.py
[('be', 3), ('is', 10), ('than', 8)]
root@kali:~/python/laowangpy# 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67

3.一文件的字節數為 102324123499123,請計算該文件按照kb與mb計算得到的大小。

>>> size = 102324123499123
>>> print "%s kb" % (size >> 10)
99925901854 kb
>>> print "%s mb" % (size >> 20)
97583888 mb
>>> print "%s gb" % (size >> 30)
95296 gb
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4.已知 a = [1,2,3,6,8,9,10,14,17],請將該list轉換為字符串,例如 ‘123689101417’.

>>> a = [1,2,3,6,8,9,10,14,17]
>>> a
[1, 2, 3, 6, 8, 9, 10, 14, 17]
>>> b = str(a)#轉換成字符串
>>> print b
[1, 2, 3, 6, 8, 9, 10, 14, 17]
>>> c = str(a)[1:-1]#去除方括號
>>> print c
1, 2, 3, 6, 8, 9, 10, 14, 17
>>> 
>>> d = str(a)[1:-1].replace(', ','')#對, 進行替換空白
>>> print d
123689101417
>>> 

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com