Python string slicing, os module practice processing

If you want to learn the slicing of strings, you need to understand the functions of strings. This article will first talk about strings. Then gather exercises, hoping to help you. Don’t forget to like it!

Common methods of string:

|-- capitalize()		# 首字母大写
|-- center()			# 居中对齐
|-- ljust()			# 左对齐
|-- rjust()			# 右对齐
|-- count()			# 统计字符串中出现的符号的次数
|-- startswith()		# 以什么开始
|-- endswith()			# 以什么结尾
|-- find()			# 查找某种符号第一次出现的位置,如果没有改符号,则返回-1
|-- index()			# 查找某种符号第一次出现的位置,如果没有改符号,则抛出异常
|-- rfind()			# 其他都一样,找最后一个
|-- rindex()			# 其他都一样,找最后一个
|-- join()			# 按照特定的符号连接元素,组成字符串
|-- split()			# 将字符串按照特定符号分隔成列表
|-- lower()			# 将字符串转换小写
|-- upper()			# 将字符串转换为大写
|-- strip()			# 清除字符串两侧的空格
|-- lstrip()			# 清除字符串左侧的空格
|-- rstrip()			# 清除字符串右侧的空格
|-- replace()			# 替换字符串
|-- title()			# 将字符串转换为符合标题格式的

translate配合maketrans可以实现简单加密效果(类似于凯撒加密)

|-- isalnum			# 只能由大小写字母、数字组成
|-- isalpha			# 只能由大小写字母
|-- isascii			# 只能由ASCII表中符号组成
|-- isdecimal			# 数字
|-- isdigit			# 数字
|-- isnumeric			# 数字
|-- isidentifier		# 有效符号
|-- islower			# 小写字母
|-- isupper			# 大写字母
|-- isprintable			# 
|-- isspace			# 是否是空格
|-- istitle			# 是否是标题

|-- encode(编码规范)		# 编码的,将字符串转换为字节数据
|-- decode()			# 解码函数,将字节转换为字符串的方法

注意:编码和解码使用同一种编码规则,推荐使用utf-8

Slicing:
ordered sequence (list, tuple, string): cutting, intercepting and other operations

sequence[start:]		# 从start位置开始截取,截取到末尾
sequence[start:end]		# [start:end),是前闭后开区间
sequence[start:end:step]	# step表示步长,注意:如果step为-1,表示从右向左切

需要注意的,切片支持负索引,如果使用负数,表示从右向左的下标

1. Separate the file path, file name and extension from the path according to the complete path

'''
作者:lsff
time:2021.1.21
'''
ls="E:\jhj\IT作业\tist.py"
def file(ls):
    way=ls[0:11]
    name=ls[11:15]
    extension=ls[16:]
    print(way,name,extension)
file(ls)

Insert picture description here

2. Get the number of Chinese characters in a string

'''
作者:lsff
time:2021.1.21
'''
ls="E:\jhj\IT作业\tist.py"
def number(l):
  
    count = 0
    for item in l:
        if 0x4E00 <= ord(item) <= 0x9FA5:
            count += 1
    return count
print(number(ls))

Insert picture description here

3. Convert all letters to uppercase or lowercase

'''
作者:lsf
time:2021.1.21
'''
ls="E:\jhj\IT作业\tist.py"
print(ls.upper())

Insert picture description here

4. Break the string according to punctuation

'''
作者:lsf
time:2021.1.21
'''
ls="E:\jhj\IT作业\tist.py"
print(ls.split("."))

Insert picture description here

5. Remove the spaces of each string in the string array

'''
作者:lsf
time:2021.1.21
'''
ls="   E:\jhj\IT作业\ist.py     "
print(ls.strip())

Insert picture description here

6. Feel free to enter a book title you think of, and then output its string length. (Len() attribute: the length of the string can be obtained)

'''
作者:lsf
time:2021.1.21
'''
book=str(input("请输入书名:"))
print(len(book))

Insert picture description here

7. Two students input their favorite game names and judge whether they are the same.
If they are equal, then output that you both like the same game; if they are not the same, output
that you two like different games.

'''
作者:lsf
time:2021.1.21
'''
perple1=str(input("请输入游戏:"))
perple2=str(input("请输入游戏:"))
for i in perple1 :
    for y in perple2 :
        if i == y :
            print("游戏一样")
        else:
            print("游戏不一样")

Insert picture description here

8. In the previous question, two students input lol and LOL to represent the same game, what should I do?

game1=str(input("请输入游戏名称:"))
game2=str(input("请输入游戏名称:"))
if game1.upper() == game2.upper():
    print("游戏一样")
else:
    print("游戏不一样")

Insert picture description here

9. Let the user enter a date format such as "2008/08/08", the date will be entered

	期格式转换为“2008-8-8日”。
	time=input("请输入日期:(格式)2009/08/08")
s1=time.split("/")
newtime="{}年-{}月-{}日".format(s1[0],int(s1[1]),int(s1[2]))
print(newtime)

Insert picture description here

10. Receive the character string input by the user, sort the characters in it (ascending
order), and output in reverse order, "cabed"→"abcde"→"edcba".

ls='cabed'
l=list(ls)
l.sort()
print(l)
l.reverse()
print(l)

Insert picture description here

11. Receive a sentence of English input by the user, and output the words in reverse order
, "hello c sharp" → "sharp c hello".

english=input("请输入一句英文:")
x=english.split(" ")
y=x[::-1]
x1=" ".join(y)
print(x1)

Insert picture description here

12. Extract the user name and domain name from the requested address
http://www.163.com?userName=admin&pwd=123456,

url='http://www.163.com?userName=admin&pwd=123456'
ls = url.split("/")
s1 = ls[2]
ls2 = s1.split("?")
print("域名是:{}".format(ls2[0]))
s1 = ls2[1]
ls3 = s1.split("&")
s1 = ls3[0]
ls4 = s1.split("=")
print("用户名是:{}".format(ls4[1]))



13.有个字符串数组,存储了10个书名,书名有长有短,现
在将他们统一处理,若书名长度大于10,则截取长度8
子串并且最后添加“...”,加一个竖线后输出作者的名字。



```clike
ls = ["我自然也欢迎您","遥远的老天爷","红尘往市不在回首嘿嘿黑","活着","白鹿原之青青草原112"] ##10个书名太多了,我只存了几个


dir = {
    
    "我自然也欢迎您":"xiaoluo","遥远的老天爷":"haoboxu","红尘往市不在回首嘿嘿黑":"xuahobo","活着":"haobo","白鹿原之青青草原112":"hahah"} 
for i in range(0,len(ls)):
    s = ls[i]
    if len(s) > 10:
        s = s[0:9]+"..._"+str(dir[ls[i]])
    ls[i] = s
print(ls)

14. Let the user enter a sentence to find out the position of all "he".

s = input("请输入一段话!")
ls = []
for i in range(0,len(s)):
    if s[i] == "呵":
        ls.append(i)

print("呵的位置是%s"%ls)

Insert picture description here

15. Let the user enter a sentence to find out all the positions of "hehe".

s = input("请输入一段话!")
ls = []
for i in range(0,len(s)-1):
    if s[i] == "呵" and s[i+1]=="呵":
        ls.append(i)

print("呵呵的位置是%s"%ls)

Insert picture description here

16. The user input of a word, this sentence is determined there is no evil, if evil
bad then it is replaced with this form of output, such as: "cow is evil", the output goes
to "cow very **" ;

word = input("请输入字符串:")
print("邪恶消失后:{}".format(word.replace("邪恶","**")))

Insert picture description here

17. Determine whether a character is a palindrome string (
interview question) "1234567654321"
"Shanghai tap water comes from the sea"

#双指针
def is_palindrome(count):
    for i in range(0,len(count)//2):
        if count[i] != count[len(count)-i-1]:
            return False
        return True
word="上海自来水来自海上"
print(is_palindrome(word))

18. Traverse the disk

import sys
import os

def file(url):
    files=os.listdir(url)
    for i in files  :
        path=os.path.join(url,i)
        if os.path.isfile(path) :
            print(path)
        elif os.path.isdir(path) :
            #如果是文件夹,递归遍历
            file(path)
if len(sys.argv) <2 :
   print("必须传递参数")
else:
    p=sys.argv[1]
    file(p)
file("E:\jhj\IT作业\Linux私房菜")

Insert picture description here

19. Use the os module to determine whether the folder [c:/a/b] exists on the disk.
If it does not exist, create a file.

import os
if not os.path.exists('c:/a/b'): #判断所在目录下是否有该文件名的文件夹
    os.makedirs('c:/a/b') #创建多级目录用mkdirs,单击目录mkdir
else:
    if os.path.exists('file'):
        print('the file exists')
    else:
        os.chdir('c:/a/b')
        os.mknod("b.txt") #创建空文件
        

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_47514459/article/details/112970514