Fundamentals 27 min read

Master Python Data Types, Operators, and String Formatting: A Complete Guide

This article provides a comprehensive overview of Python fundamentals, covering built‑in data types, number representations, base conversions, arithmetic and logical operators, operator precedence, common math functions, string manipulation techniques, and multiple approaches to string formatting.

Ops Development Stories
Ops Development Stories
Ops Development Stories
Master Python Data Types, Operators, and String Formatting: A Complete Guide

Python Data Types

Number (数字)

String (字符串)

List (列表)

Dictionary (字典)

Tuple (元组)

Set (集合)

Numbers, strings, and tuples are immutable; lists and dictionaries are mutable. Reassigning an immutable variable actually creates a new object and redirects the name to it.

Numbers

int: integer

1. 正负数
2. 十六进制 (0x or 0X, e.g., 0xff)
3. 八进制 (0o or 0O, e.g., 0o632457)
4. 二进制 (0b or 0B, e.g., 0b101100)

fraction: 分数

float: 浮点数

complex: 复数

bool: 布尔型 (True or False)

Base Conversion

Integer to other bases

Use bin(i), oct(i), hex(i) to convert decimal to binary, octal, or hexadecimal.

>> s=10
>>> bin(s)
'0b1010'
>>> oct(s)
'0o12'
>>> hex(s)
'0xa'

Convert non‑decimal strings to integers with int(str, base) where base can be 2, 8, 16, up to 36.

>> int('0b10010', 2)
18
>>> int('0o52415', 8)
21773
>>> int('0x134ab', 16)
79019
>>> int('s', 32)
28
>>> int('yz', 36)
1259

Hexadecimal can also be converted to binary or octal, and vice‑versa.

>> hex(0b1001)
'0x9'
>>> oct(0b101)
'0o5'
>>> bin(0xff)
'0b11111111'

Operators

Arithmetic: +, -, *, /, //, %, ** Comparison: ==, !=, >, <, <=, >= Assignment: =, +=, -=, *=, /=, %=, //=, **= Bitwise: &, |, ^, ~, <<, >> Logical: and, or, not Membership: in, not in Identity:

is, is not
>> a=12
>>> f=~a
>>> f
-13
>>> bin(a)
'0b1100'
>>> bin(a<<1)
'0b11000'
>>> bin(a>>1)
'0b110'
>>> lst=[1,2,3,4,5]
>>> a=3
>>> a in lst
True
>>> a not in lst
False
>>> b=a[:]
>>> b is a
False

Operator Precedence

** (exponentiation) – highest

~, +, - (unary)

*, /, //, %

+, -

<<, >>

&

^, |

<=, >=, <, >

==, !=

=, +=, -=, *=, /=, //=, %=, **=

Math Functions

power: same as

**
>> pow(2,3)
8

sqrt: square root

>> import math
>>> math.sqrt(4)
2.0

max, min: maximum and minimum

>> max(2,3,4,5,1,9,6)
9
>>> min(2,3,4,5,1,9,6)
1

abs, math.fabs: absolute value (float version)

round: round to nearest, ties to even

math.ceil / math.floor: ceiling and floor

cmp (Python 2): returns -1, 0, 1 for comparison

random module: random.random(), random.choice(), random.sample(), random.shuffle(), random.getrandbits() math.modf: separate fractional and integer parts

math.log, math.log2, math.log10: logarithms with optional base

Decimal module for precise decimal arithmetic

Strings

Python 2 uses ASCII by default; Unicode strings are prefixed with u. Python 3 uses Unicode.

String Literals

Single quotes: 'str' Double quotes: "str" Triple quotes for multi‑line strings

Escape characters: "\t", "\n" Raw strings:

r"C:\path\file"

String Operations

Concatenation

>> 'abc' + 'def'
'abcdef'
>>> 'hello' * 5
'hellohellohellohellohello'

Indexing & Slicing

>> text = 'this_is_str'
>>> text[0:4]
'this'
>>> text[5:7]
'is'
>>> text[:4]
'this'
>>> text[-3:]
'str'
>>> text[::2]
'ti_ssr'
>>> text[8:1:-2]
'ss_i'

Encoding Conversion

>> ord('d')
100
>>> chr(99)
'c'
>>> ord('王')
29579
>>> chr(29579)
'王'

Case Conversion (manual)

>> Text = ''
>>> text = "aSdFgHjK"
>>> for i in text:
...     i_code = ord(i)
...     if 97 <= i_code <= 122:
...         Text += chr(i_code-32)
...     else:
...         Text += i
>>> Text
'ASDFGHJK'

Case Conversion (built‑in methods)

capitalize()

: first character uppercase title(): first character of each word uppercase upper(), lower(),

swapcase()

Alignment and Padding

>> 'hello'.center(11)
'   helloo  '
>>> 'hello'.ljust(11, '_')
'helloo_____' 
>>> 'hello'.rjust(11, '_')
'_____hello'

Whitespace Handling

>> 'hello\tworld'.expandtabs(9)
'hello    world'
>>> 'sad'.zfill(10)
'0000000sad'

Trimming

>> '  hello world  '.strip()
'hello world'
>>> 'hello,world'.strip('h')
'ello,world'

Searching

startswith()

/

endswith()
count()
find()

/

rfind()
index()

/

rindex()
replace(old, new, count)

Character Classification

isalpha()

, isdigit(), isalnum(), islower(), isupper(), isspace(), istitle(), isdecimal(), isnumeric(), isidentifier(),

isprintable()

Splitting

>> 'asd,fgh,jkl'.split(',')
['asd', 'fgh', 'jkl']
>>> 'asd,fgh,jkl'.rsplit(',', 1)
['asd,fgh', 'jkl']
>>> 'asd
fgh
jkl'.splitlines()
['asd', 'fgh', 'jkl']
>>> 'http://www.baidu.com'.partition('://')
('http', '://', 'www.baidu.com')

Joining

>> '-'.join('asdfg')
'a-s-d-f-g'

String Formatting

Three common methods:

Percent‑style ( %) str.format() f‑strings

Percent‑style

>> "%s|%r|%c" % ("this is str", "this is repr", "C")
"this is str|'this is repr'|C"
>>> "%d|%o|%x|%X|" % (3, 12, 13, 14)
'3|14|d|E|'
>>> "%+10.2f" % 3.1
'     +3.10'
>>> "%#8x" % 10
'    0xa'

str.format()

>> "{0}'s password is {1}".format('wanger', 123456)
"wanger's password is 123456"
>>> "{1}'s password is {0}".format(123456, 'wanger')
"wanger's password is 123456"
>>> "{:.4f}".format(3.1415926)
'3.1416'
>>> "{0:b},{0:o},{0:x}".format(10)
'1010,12,a'
>>> "{0:#b},{0:#o},{0:#x}".format(10)
'0b1010,0o12,0xa'
>>> "{:,}".format(100000000000)
'100,000,000,000'

f‑strings

>> name = 'wanger'
>>> age = 25
>>> f"Hello, I'm {name}, age {age}"
"Hello, I'm wanger, age 25"
>>> f"{2*3}"
'6'
>>> f"{name.lower()} is funny"
"wanger is funny"
>>> comedian = {'name':'wanger','age':25}
>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
"The comedian is wanger, aged 25."

Practical Use Cases

Splitting with multiple delimiters using re.split():

>> import re
>>> re.split(r'[;,\s]\s*', 'asd,dfg;zxc ert  uio')
['asd', 'dfg', 'zxc', 'ert', 'uio']

Checking prefixes/suffixes:

>> url = 'http://www.baidu.com'
>>> url.startswith(('http://', 'ftp://'))
True
>>> filename = 'resource.txt'
>>> filename.endswith('txt')
True

Shell‑style pattern matching with fnmatch:

>> from fnmatch import fnmatch, fnmatchcase
>>> fnmatch('log.txt', '*.txt')
True
>>> fnmatchcase('log.TXT', '*.txt')
False
>>> fnmatchcase('log.TXT', '*.TXT')
True

Regular‑expression date conversion:

>> import re
>>> date = 'today is 13/12/2018'
>>> re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\2-\1', date)
'today is 2018-12-13'
>>> pattern = re.compile(r'(\d+)/(\d+)/(\d+)')
>>> pattern.sub(r'\3-\2-\1', date)
'today is 2018-12-13'
>>> pattern.subn(r'\3-\2-\1', 'yestory is 12/12/2018,today is 13/12/2018')
('yestory is 2018-12-12,today is 2018-12-13', 2)

Case‑insensitive search and replace:

>> import re
>>> re.findall('replace', 'Replace,replace,REPLACE')
['replace']
>>> re.findall('replace', 'Replace,replace,REPLACE', flags=re.IGNORECASE)
['Replace', 'replace', 'REPLACE']
>>> re.sub('replace', 'WORD', 'Replace is the same as REPLACE', flags=re.IGNORECASE)
'WORD is the same as WORD'
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Data TypesoperatorsString Methods
Ops Development Stories
Written by

Ops Development Stories

Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.