Python初级学习20230902——字符串

字符串

"""
example05 - 字符串
1.转义问题
2.字符编码
Author: danlis
Date: 2023/9/2
"""
a = 'hello, world'
# 和a一样的
b = "hello, world"
# 一般长字符串,用三个单引号。三个双引号一般作为注释
c = '''
hello, 
world
'''

# 引号中加引号,则用转义字符。\转义
print("abcdef\b退格\t空格\n换行\\输出反斜杠")
# 写Windows地址的时候,写/正斜杠
# 直接输出原始字符串。字符串前面加 r,不进行转义字符的判断
d = r'c:\nei\rong\hello.py'
print(d)
# 如果需要输出\,则需要加\转义
d = 'c:\\nei\\rong\\hello.py'
print(d)

# 带占位符的字符串(格式化字符串)
e = f'文件路径:{d}'
print(e)

# Python中还允许\后面还可以跟一个八进制或者十六进制\x来表示字符
# \141是表示八进制数141,字符是a
# \x61表示的是十六进制61,字符也是a
a = '\141\142\x61\x62'
print(a)

# ASCII ---> 国标码GB2312 ---> GBK国标扩 ---> Unicode万国码(UTF-8)
# 另外一种表示字符的方式是在\u后面跟Unicode字符编码
# Unicode是四个值的\uXXXX
a = '\u8345'
print(a)

例题

# example1
# 一个列表中有很多重复元素,写一段代码去掉列表中的重复元素
# list1 = [random.randrange(1, 100) for _ in range(20)]
list1 = [96, 79, 89, 47, 92, 13, 42, 33, 86, 54, 3, 3, 5, 5]

# 我的做法
list1.sort()
print(list1)
list2 = [list1[0]]
for i in range(1, len(list1)):
    if list1[i - 1] != list1[i]:
        list2.append(list1[i])
print(list2)

# 第二个做法
list1 = [96, 79, 89, 47, 92, 13, 42, 33, 86, 54, 3, 3, 5, 5]
print(list1)
unique_items = []
for value in list1:
    if value not in unique_items:
        unique_items.append(value)
print(unique_items)
posted @ 2023-09-02 15:40  Danlis  阅读(23)  评论(0编辑  收藏  举报