Hello! 欢迎来到小浪资源网!



Python Day-csv 文件、字符串方法、ASCII、任务


Python Day-csv 文件、字符串方法、ASCII、任务

csv 文件:
–>逗号分隔文件。
–> 是纯文本格式,由逗号分隔一系列值。
–>它将所有行和字段存储在行和列中
–>可以用windows中任何文本编辑器打开。

格式:

f =open("sample.txt", "r")  with open("sample.txt",’r’) as f: 

r-read:打开文件进行读取
w-write:打开文件进行写入。创建一个新文件或覆盖现有文件。
rb-read 二进制文件:用于读取二进制文件,如图像、视频、音频文件、pdf 或任何非文本文件。

示例:
分数.csv:

player,score virat,80 rohit,90 dhoni,100 

来自另一个模块:

import csv f =open("score.csv", "r") csv_reader = csv.reader(f) for row in csv_reader:     print(row) f.close() 

输出:

['player', 'score'] ['virat', '80'] ['rohit', '90'] ['dhoni', '100']  

ASCII
美国信息交换标准码(ascii)

ascii 表:
参考:https://www.w3schools.com/charsets/ref_html_ascii.asp

48-57 – 数字
65-91 – 从头到尾
97-122- a 到 z

ord-ordinal–>查找 ascii 数字
chr-character–>将数字转换为字符

使用 ascii 形成模式:
1)

for row in range(5):     for col in range(row+1):         print(chr(col+65), end=' ')     print() 

输出:

a  a b  a b c  a b c d  a b c d e  

2)

for row in range(5):     for col in range(5-row):         print(chr(row+65), end=' ')     print() 

输出:

a a a a a  b b b b  c c c  d d  e  

使用 for 循环while 循环打印名称:
方法一:

name = 'guru' for letter in name:     print(letter,end=' ') 

方法2:

name = 'guru' i = 0 while i<len(name):     print(name[i],end=' ')     i+=1 

输出:

g u r u 

使用 ascii 的字符串方法:
1.大写: 将第一个字符转换为大写。

txt = "hello, and welcome to my world."  first = txt[0] if first>='a' and first<='z':     first = ord(first)-32     first = chr(first)  print(f"{first}{txt[1:]}") 

输出:

hello, and welcome to my world. 

2。 casefold:字符串转换为小写。

txt = "guruprasanna!"  for letter in txt:     if letter>='a' and letter<'z':         letter = ord(letter)+32         letter = chr(letter)     print(letter,end='') 

输出:

guruprasanna! 

3。计数: 返回指定值在字符串中出现的次数。

txt = "i love apples, apple is my favorite fruit" key = 'apple' l = len(key) count = 0 start = 0  end = l while end<len(txt):     if txt[start:end] == key:         count+=1     start+=1     end+=1 else:     print(count) 

输出:

2 
#first occurrence of given key txt = "i love apples, apple is my favorite fruit" key = 'apple' l = len(key) start = 0  end = l while end<len(txt):     if txt[start:end] == key:         print(start)         break     start+=1     end+=1 

输出:

7 
#last occurrence of given key txt = "i love apples, apple is my favorite fruit" key = 'apple' l = len(key) start = 0  end = l final = 0 while end<len(txt):     if txt[start:end] == key:         final = start     start+=1     end+=1 else:     print(final) 

输出:

15 

任务:
查找给定输出的程序:

1   2   3   4   5   6   7    1   2   3   4   5 1   2   3 1 

输入:

for row in range(4):     for col in range(7-(row*2)):         print((col+1), end=' ')     print() 

相关阅读