Python-字符串的拼接与函数

#字符串拼接(%):

a = 'i am %s, age %d' %('alex', 12)  #中间不需要用逗号分隔,多个参数后面加括号
print(a)
# --> i am alex, age 12
    # %s是万能的,可接收一切类型;%d则只能取整型。使用不同类型的可读性强,故一般不全都使用%s
    # %s 字符串
    # %d 整型
    # %f 浮点数

#打印百分号(%): %%

#字典形式的拼接:

a = {'name':'alex', 'age':18}
print('my name is %(name)s, age is %(age)d' %a)#注意%(name)s,%(age)d,后面s/d不能忽略

#多字符串拼接(sep):

print('root','x','0','0', sep=':')
# --> root:x:0:0

# format格式化:

print('i am {}, age {}'.format('ad',12))
# -->  i am ad, age 12
print('i am {1}, age {0}'.format('ad',12))
# -->  i am 12, age ad
print('i am {1}, age {1}'.format('ad',12))
# -->  i am 12, age 12

  #format中使用列表或元组时,必须加一个*

print('i am {}, age {}'.format(*['alex',18]))
print('i am {}, age {}'.format(*('alex',18)))

  #format中使用字典时,必须加两个**

a = {"name":'alex', 'age':18}
print('i am {name}, age {age}'.format(**a))

    #下面方法与上面字典结果一样:

print('i am {name}, age {age}'.format(name='alex', age=18))  #注意name,age 不加引号

# format对数字的不同处理方法:

print('{:b}, {:o}, {:d}, {:x}, {:X}, {:%}'.format(15,15,15,15,15,15))
#:b二进制  :o八进制 :d十进制  :x十六进制(小写字母)  :X十六进制(大写字母)  :%显示百分比
# --> 1111, 17, 15, f, F, 1500.000000%

### 函数 ###

#函数定义方法:

def test(x):
    "the function definitions"  #功能注释
    x += 1
    return x

#返回值:
    如果没有返回值则返回None

  返回值只有一个:返回该值

  返回值有多个:返回一个元组,(可同时使用多个变量来分开获取)

#位置参数和关键字参数:

test(1,2,3)         #位置参数,需一一对应
test(y=2, z=3, x=1) #关键字参数,不需一一对应
test(1,2, z=3)     #两种参数同时存在时,关键字参数必须在最右边

#默认参数:

def test(x,y,z='zzz'):   # z为默认参数,不传入该参数则使用默认值

#参数组(**字典  *列表):

  *args       #传位置参数,生成元组

def test(x,*args):  #前面正常赋值,然后将多余的转换成元组保存在args
    print(x, args)
test(1,2,3,4)
# --> 1 (2, 3, 4)

  **kwargs    #传关键字参数,生成字典

def test(x,**kwargs):
    print(x,kwargs)
test(1,z=3, y=2)
# --> 1 {'z': 3, 'y': 2}

#列表或元组类型的实参的两种传入方式:

test(1,['x','y','z'])     #不加*,该列表整体作为一个参数保存在元组
# --> 1 (['x', 'y', 'z'],)
test(1,*['x','y','z'])    #加*,将该列表各个元素分开,保存在元组
# --> 1 ('x', 'y', 'z')
原文地址:https://www.cnblogs.com/yu-long/p/9945775.html