#字符串格式化
def format_string():
'''
format()方法 是一种传统的字符串格式化方法
它使用占位符{}俩表示要插入的变量或值,并通过传递参数来替换这些占位符
'''
#基本使用方法
msg = 'My name is {},age is {}.'.format('Tom',22)
print(msg)
msg = 'My name is {},age is {}.'.format('Jack',23)
print(msg)
#位置参数格式化字符串
msg = 'My name is {0},age is {1}.'.format('Tom',22)
print(msg)
msg = 'My age is {1},name is {0}.'.format('Tom',22)
print(msg)
msg = 'My age is {3},name is {0}.My age is {3},name is {0}.My age is {3},name is {0}.'.format('Tom',22,0,52)
print(msg)
#关键字参数
msg = 'My name is {name},age is {age}.'.format(name='Tom',age=22)
print(msg)
username = 'Alice'
msg = 'My name is {name},age is {age}.My name is {name},age is {age}.My name is {name},age is {age}.'.format(name=username,age=22)
print(msg)
#格式化字符串时,指定格式化选项
pi = 3.141592659589793
formatted_pi = 'The value of pi is approximately {:.2f}'.format(pi)
print(formatted_pi)
#字符串对齐
print('The value is ljust |{:5}|'.format('abc'))
print('The value is ljust |{:<5}|'.format('abc'))
print('The value is ljust |{:>5}|'.format('abc'))
#数字对齐
print('The value is ljust |{:5}|'.format('11'))
print('The value is ljust |{:<5}|'.format('11'))
print('The value is ljust |{:>5}|'.format('11'))
'''
f-string字符串 是3.6及更高版本引入的一种简洁直观的字符串格式化方法
它使用前缀f定义字符串,并使用{}来插入变量值
'''
#基本用法
name = 'Tony'
age = 656
msg = f'My name is {name},age is {age}.'
print(msg)
#字符串对齐
print(f'The value is ljust |{"acb":5}|')
print(f'The value is ljust |{"acb":<5}|')
print(f'The value is ljust |{"acb":>5}|')
#格式化字符串时,指定格式化选项
pi = 3.141592659589793
formatted_pi = f'The value of pi is approximately {pi:.2f}'
print(formatted_pi)
#在f-string中,可以使用表达式和函数调用来生成动态的字符串内容
name = 'Alice'
age = 25
greeting = f'{"Hello" if age < 30 else "Hi"} {name.upper()}'
print(greeting)
#sql_string = f"""select * from user where id > {sid} and name = {name}"""