Strings and lists of Python series

            Thanks for likes and attention, a little progress every day! come on!

Table of contents

1. String

1.1 Definition and input of character string

1.2 String splicing and formatted output

1.3 Subscript of string

1.4 Slicing and reversing of strings

1.5 Common operations on strings

2. List-List

2.1 Common operations on lists

2.2 List merging and splicing

2.3 List nesting

3. Tuple-Tuple

4. Dictionary-Dictionary


Learning record of Python series articles:

Windows environment installation and configuration of Python series

Variables and operators of Python series

Judgment and cycle of Python series - Blog - CSDN Blog

Python series of strings and lists - blog driving tractor home - CSDN blog

File Operations and Functions of the Python Series

Detailed explanation of the standard library OS of Python series modules - Programmer Sought

Detailed explanation of the standard library re of Python series modules - Programmer Sought

Detailed explanation of the standard library json of Python series modules - Programmer Sought

Detailed explanation of the standard library shutil of Python series modules - Programmer Sought


1. String


1.1 Definition and input of character string


In python, everything enclosed in quotes is a string. There are also input function input, str() function conversion, etc.

string1 = "hello"
string2 = 'hello'
string3 = """hello
python"""
string4 = '''hello
world'''
string5 = input("input anything: ")
string6 = str(18)

print(isinstance(string3, str)) # isinstance函数可以用来判断数据是否为某一个数据类型,返回值为True或False

Results of the:

1.2 String splicing and formatted output


Example:

name = "张三丰"
age = 95

# print("name,你五年后age+5岁了")	
print(name+",你五年后 " + str(age + 5) + " 岁了")

print("%s,你五年后 %d 岁了" % (name, age + 5))

Results of the:

1.3 Subscript of string


Strings, lists, and tuples all belong to == sequence == (sequence), so they will all have subscripts.

What is a subscript (index)?

Example: Traverse and print a string

str1 = "kang"

# index 从 0 开始
for index, i in enumerate(str1):
    print("第 %d 个字符是 %s. " % (index, i))
print("++++++++++++++++++++")
# index 从 1
for index, i in enumerate(str1):
    print("第 %d 个字符是 %s. " % (index+1, i))
print("++++++++++++++++++++")
index = 0
for i in str1:
    print("第 %d 个字符是 %s. " % (index+1, i))
    index += 1

Results of the:

1.4 Slicing and reversing of strings


Example:

str2 = "kangLH"

# 倒序 HLgnak
print(str2[::-1])
# 输出:gn
print(str2[3:1:-1])
# 输出:ang
print(str2[1:4])

Results of the:

1.5 Common operations on strings


Example:

str1 = "hadoop kafka hive range hbase azkaban"

# 拆分 
a = str1.split(" ")
num = 0
for i in a:
    print(num, i, end="\t") # 拆分的字符串打印
    for index in i:
        print(index, end=", ") # 拆分字符串的字符打印
    num += 1
    print()


print(len(str1))		        # 调用len()函数来算长度	             (常用)
print(str1.__len__())			# 使用字符串的__len__()方法来算字符串的长度

print(str1.capitalize())		# 整个字符串的首字母大写
print(str1.title())		        # 每个单词的首字母大写
print(str1.upper())			# 全大写
print(str1.lower())	        	# 全小写
print("HAHAhehe".swapcase())	# 字符串里大小写互换

print(str1.center(50,"*"))		# 一共50个字符,字符串放中间,不够的两边补*
print(str1.ljust(50,"*"))		# 一共50个字符,字符串放左边,不够的右边补*	      
print(str1.rjust(50,"*"))		# 一共50个字符,字符串放右边,不够的左边补*

print(" haha\n".strip())		# 删除字符串左边和右边的空格或换行	(常用,处理文件的换行符很有用)
print(" haha\n".lstrip())		# 删除字符串左边的空格或换行
print(" haha\n".rstrip())		# 删除字符串右边的空格或换行

print(str1.endswith("you"))		# 判断字符串是否以you结尾	    类似于正则里的$	(常用)
print(str1.startswith("hello"))	# 判断字符串是否以hello开始	类似于正则里的^	(常用)

print(str1.count("e"))			# 统计字符串里e出现了多少次		               (常用)

print(str1.find("hive"))		# 找出nice在字符串的第1个下标,找不到会返回-1
print(str1.rfind("e"))		# 找出最后一个e字符在字符串的下标,找不到会返回-1
print(str1.index("hive"))	# 与find类似,区别是找不到会有异常(报错)		    (常用)
print(str1.rindex("e"))		# 与rfind类似,区别是找不到会有异常(报错)

print(str1.isalnum())		# 判断是否为数字字母混合(可以有大写字母,小写字母,数字任意混合)
print(str1.isalpha())		# 判断是否全为字母(分为纯大写,纯小写,大小写混合三种情况)
print(str1.isdigit())		# 判断是否为纯数字
print(str1.islower())		# 测试结果为:只要不包含大写字母就返回True
print(str1.isupper())        # 测试结果为:只要不包含小写字母就返回True
print(str1.isspace())		# 判断是否为全空格

print(str1.upper().isupper())	# 先把str1字符串全转为大写,再判断是否为全大写字母,结果为True

Of course, there are many methods for strings, we can use PyCharm Lenovo to find them directly.


2. List-List


Sequences are the most basic data structures in Python. Each element in a sequence is assigned a number - its position, or index, with the first index being 0, the second index being 1, and so on. Python has six built-in types for sequences, but the most common are lists and tuples.

Operations that can be performed on sequences include indexing, slicing, adding, multiplying, and checking membership.

A list is the most commonly used Python data type, which can appear as a comma-separated value enclosed in square brackets.

The data items of a list do not need to have the same type.

To create a list, simply enclose the different data items separated by commas in square brackets. As follows:

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

2.1 Common operations on lists


The addition, deletion, modification and query operations of the list, the list is a variable data type, and can be added, deleted, and modified.

Example:

str_list = ["kafka", "hadoop", "hadoop", "hive", "range", "flink", "hbase"]

print(str_list)
print("列表长度: ", len(str_list))

# 修改 原来的元素
str_list.append("azkaban")
print("追加: " + str(str_list))

# 移除
str_list.remove("hive")
print("移除: " + str(str_list))

# c插入
str_list.insert(0,"yarn")
print("插入: " + str( str_list))

# 统计次数
cnt = str_list.count("hadoop")
print("hadoop出现的次数: ", cnt)

# 统计次数
a = str_list.index("hadoop")
print("hadoop第一次出现的索引位: ", a)

Results of the:

2.2 List merging and splicing


We can concatenate two lists into one.

Example:

list1 = ["haha", "hehe", "heihei"]
list2 = ["xixi", "hoho"]

list1.extend(list2)    		# list1 += list2也可以,类似字符串拼接
print(list1)
print("++++++++++++++++++++++++++++++++++++++++++")


list3 = list1 + list2         # 上面list1 再拼接 list2
print(list3)

Results of the:

2.3 List nesting


Example:

# 列表里可以嵌套列表,也可以嵌套其它数据类型
emp = [["张三丰", 18000], ["张无忌", 16000], ["南乔峰", 20000], ["慕容复", 15000]]  

# 循环打印出人名与其对应的工资
for i in emp:
    print("%s 的工资是%d." % (i[0], i[1])) 

Results of the:


3. Tuple-Tuple


Tuples in Python are similar to lists, except that the elements of the tuple cannot be modified.

Use parentheses for tuples and square brackets for lists. Tuple creation is very simple, just add elements in parentheses and separate them with commas. Tuples are read-only, which does not mean that any data in the tuple is immutable. If there is a list in the tuple, then the list is mutable.

str_tup = ("kafka", "hadoop", "hadoop", "hive", "range", "flink", "hbase")
print(str_tup)
print("列表长度: ", len(str_tup))

# 统计次数
cnt = str_tup.count("hadoop")
print("hadoop出现的次数: ", cnt)

# 统计次数
a = str_tup.index("hadoop")
print("hadoop第一次出现的索引位: ", a)

print("+++++++++++++++++++++++++++++++")
tuple1 = (1, 2, 3, 4, 5, 1, 7)

print(tuple1)
print("类型: ", type(tuple1))
print("返回元组中元素最大值: ", max(tuple1))
print("返回元组中元素最小值: ", min(tuple1))
print("打印3这个元素在元组里的下标: ", tuple1.index(3))
print("统计1这个元素在元组里共出现几次: ", tuple1.count(1))
print("返回元组中元素【2-5)", tuple1[2:5])

Results of the:


4. Dictionary-Dictionary


Dictionaries are another mutable container model and can store objects of any type.

Each key-value key:value pair of the dictionary is separated by a colon :, each key-value pair is separated by a comma , and the entire dictionary is included in curly braces {} , the format is as follows:

d = {key1 : value1, key2 : value2 }

Note: dict is a keyword and a built-in function of Python, and the variable name is not recommended to be named dict .

The key is generally unique. If the last key-value pair is repeated, it will replace the previous one. The value does not need to be unique.

Example:

dict1 = {
    'stu01': "张三丰",
    'stu02': "张无忌",
    'stu03': "夫子",
    'stu04': "昊天",
}

print(type(dict1))
print(len(dict1))
print(dict1)

for i in dict1.items():
    print(i)

for i in dict1.items():
    print(i[0],  i[1])
    if i[1] == "张无忌":
        dict1[i[0]] = "郭靖"
print("张无忌改为郭靖: ", dict1)
print("查询stu03: ", dict1.get("stu03"))
dict1["stu05"] = "谢逊"
print("新增 stu05: ", dict1)

# 删
dict1.pop("stu01")
print("删除 stu01: ", dict1)

Results of the:

Python dictionaries include the following built-in methods:

Guess you like

Origin blog.csdn.net/qq_35995514/article/details/130753771