Python Basic Data Types: Strings, Numbers, Lists, Tuples, and Dictionaries with Examples
This article introduces Python’s fundamental data types—including strings, numbers, lists, tuples, and dictionaries—explaining their characteristics, common operations, built‑in methods, and providing clear code examples for each concept; it also covers escape sequences, slicing, concatenation, formatting, and basic arithmetic operators, helping beginners grasp essential Python programming constructs.
String Type
A string is a sequence composed of one or more elements.
Strings are typically delimited by single quotes, double quotes, triple single quotes, or triple double quotes.
Escape Characters
r disables escape sequences
\n newline
\b backspace
\r carriage return
\t tab
\? a question mark
Practice Code
str1 = "Hello World !"
str2 = ''' ssss
sssssss'''
print(str1,str2)
str3 = "你好 中国"
print(str3)
# slicing
str4 = "hello I am zhangsan!"
print(str4[8])
print(str4[:5]) # end index is exclusive, start index 0 can be omitted.
print(str4[5:]) # start index includes the element at position 5.
print(str4[-10:-1])
# concatenation
str5 = "Hello"
str6 = "World !"
str7 = "123"
print(str5 + ' ' + str6 + str7) # string concatenation cannot mix with int types
# string formatting
name = "zzzz"
age = 123
newage = str(age) # str() converts to string
print(type(newage))
print("my name is %s, my age is %d" %(name,age)) # %s for string, %d for number
msg = "my name is {0}, my age is {1}".format(name,age)
print(msg)
# escape characters
new1 = r"abc
cba"
print(new1)Built-in Functions
capitalize()
count()
decode()
encode()
endswith()
startswith()
find()
index()
isalpha()
lstrip()/rstrip()/strip()
replace()
upper()
split()
reponse = " abcd123 45abcd "
print(reponse.capitalize()) # capitalize first character
print(reponse.count('b',2,len(reponse))) # count occurrences of 'b' between positions
print(reponse.encode(encoding="UTF-8")) # encode string with UTF-8
newreponse = reponse.encode(encoding="UTF-8")
print(newreponse.decode(encoding="UTF-8")) # decode back to string
print(reponse.startswith("b")) # check prefix
print(reponse.endswith("c")) # check suffix
print(reponse.find("ac")) # find substring, returns -1 if not found
print(reponse.index('b')) # return index of first occurrence
print(reponse.isalpha()) # check if all characters are alphabetic
print(reponse.lstrip()) # remove leading spaces
print(reponse.rstrip()) # remove trailing spaces
print(reponse.strip()) # remove both leading and trailing spaces
print(reponse.replace(" ","")) # replace double spaces
print(reponse.upper()) # convert to uppercase
print(reponse.split(" ")) # split by double spaces into listNumeric Types
Categories
Integer
Boolean
Float
Complex
Operators
+ - * / % > = < >= <= ==Practice Code
age = 45 # positive integer
memory = -100 # negative integer
a = 0x768A # hexadecimal integer
print("my age is : %d, my memory is : %d" % (age,memory))
print(a)
a = True
b = False
print(int(a),int(b))
c = 1.2
d = 2.4
print(c,type(d))
a = 123
b = 456
print("a + b = " + str(a+b) )
print("a - b = " + str(a-b))
print("a * b = " + str(a*b))
print("a / b = " + str(a /b) )
print("a > b " + str(a > b))
print("a < b " + str(a<b))List Type
Built-in Functions
append()
count()
extend()
index()
insert()
pop()
remove()
reverse()
Practice Code
## definition
a = []
print(type(a))
numlist = [1,2,3,4,5,6]
strlist = ["a","b","c","d"]
print(numlist,strlist)
## access elements
print(numlist[3],strlist[2])
print(numlist[:5])
print(len(numlist))
## application
ipAddress = [r"192.158.0.1",r"192.168.0.2"]
print(ipAddress)
## iteration
for ip in ipAddress:
print(ip)
# built-in functions
testHosts = ["aa","bb","cc","dd"]
t1 = ["dd","cc"]
testHosts.append("EE") # append at end
print(testHosts.count('bb')) # count occurrences
print(testHosts.extend(t1)) # extend list
print(testHosts.index("EE")) # get index of element
testHosts.insert(5,"DD") # insert at position 5
print(testHosts)
print(testHosts.pop(2)) # pop element at index 2
print(testHosts)
testHosts.remove("EE") ## remove element
print(testHosts)
testHosts.reverse() # reverse list
print(testHosts)Tuple Type
Elements in a tuple are immutable.
# definition
a = ()
print(type(a))
a = (1,2,3,4,5)
b = ("aa","bb","cc")
print(a,b)
# usage
test = ("java","tomcat","springboot")
print(test[1])
print(test[:2])
test1 = ([1,2,3],"aa")
print(test1)
test1[0].append(123)
print(test1)Dictionary Type
key/value pairs
Built-in Functions
clear()
copy()
get()
items()
keys()
update()
pop()
values()
Practice Code
# definition
a = {}
print(type(a))
myinfo = {"name":"zhangsan","age":45}
print(myinfo)
print(myinfo['name'])
myinfo["job"] = "devops1" # add or modify element
print(myinfo)
# built-in functions
myinfo = {"name":"zhangsan","age":45}
#print(myinfo.clear()) # clear dictionary
print(myinfo)
data1 = myinfo.copy() # copy independent version
print(data1)
data1["name"] = "lisi"
print(data1)
print(myinfo)
print(myinfo.get("name")) # get value by key
print(myinfo.items()) # return view of (key, value) tuples
print(type(myinfo.items()))
print(myinfo.keys()) # get all keys
print(myinfo.values()) # get all values
print(myinfo.pop("name")) # remove entry by key
print(myinfo)Practical 1 – Python Formatted Output
## %
name = "zhangsan"
age = 45
print("my name is : %s , my age is %s" % (name,str(age)))
## format
name = "lisi"
age = 34
print("my name is {0}, my age is {1}".format(name,age))
## title
info = """
name = {0}
age = {1}
high = {2}
jobs = {3}
address = {4}
"""
print("---------------------")
print(info.format("zhangsan",24,178,"PythonDeveloper","Beijing"))
print("---------------------")Practical 2 – List CRUD Operations
## append
## remove pop
students = ["zhangsan","lisi","wangwu"]
## add a student
newStudent = "aa"
students.append(newStudent)
print("class students is : %s " %(students,))
## merge classes
twoStudents = ["cc","dd","ee"]
students.extend(twoStudents)
print("class students is : %s " %(students,))
## remove a student
moveStudent = "wangwu"
students.remove(moveStudent)
print("class students is : %s " %(students,))
## update
studentName = "zhangsanfeng"
stuindex = students.index("zhangsan")
students[stuindex] = studentName
print("class students is : %s " %(students,))Practical 3 – Converting JSON Data to a Dictionary
import json
## dict -> json
myinfo = {"name":"zhangsan","age":100}
jsonInfo = json.dumps(myinfo)
print(type(jsonInfo))
## json -> dict
dictInfo = json.loads(jsonInfo)
print(type(dictInfo))
print(dictInfo['age'])
##
a = '{"name":"zhangsan"}'
print(json.loads(a))Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
