Python(5):字符串学习

1.format()方法

print('{0:.3f}'.format(1/3))       #将1/3保留三位小数输出
print('{0:%}'.format(1/4))         #将1/4格式化为百分数输出
print('{0:.1%}'.format(1/4))       #.表示的是保留小数点后几位
print("The number {0} in hex is: {0:#x}, in oct is {0:#o}".format(55))        #冒号后面#x和x、#o和o的区别,在输出的时候,带#的会在数字前加上Ox,Oo。如果大写x,那么最后十六进制数的字母为大写。
print("The number {0:,} in hex is {0:x}, The number {1} in oct is {1:o}".format(5555, 55)) #0和1 代表的是格式化的是format()中的第几位数字。
print("The number {1} in hex is {1:#x}, the number {0} in oct is {0:#o}".format(5555, 55))
print("My name is {name}, my age is {age}, and my QQ is {qq}".format(name='Li', qq=236030, age='60'))
position = (5, 8, 13)
print("x:{0[0]}, y:{0[1]}, z:{0[2]}".format(position))
print("{0:_},{0:_x}".format(1000000))#将一些较大的数字进行分隔,方便读数
print('{:*^30}'.format('Congratulations')) #表示输出宽度约束为30个字符,…^符号表示居中对齐,用*进行填充
print('{:*<30}'.format('Congratulations'))#表示居左对齐
print('{:*>30}'.format('Congratulations'))#表示居右对齐
print('{:.^30}'.format('Congratulations'))#用.进行填充

结果如下:

0.333
25.000000%
25.0%
The number 55 in hex is: 0x37, in oct is 0o67
The number 5,555 in hex is 15b3, The number 55 in oct is 67
The number 55 in hex is 0x37, the number 5555 in oct is 0o12663
My name is Li, my age is 60, and my QQ is 236030
x:5, y:8, z:13
1_000_000,f_4240
*******Congratulations********
Congratulations***************
***************Congratulations
.......Congratulations........

2.进行排版

s = "Congratulations".center(20,'-')
print(s)
s = "Congratulations".rjust(20,'~')
print(s)
s = "Congratulations".ljust(20,'*')
print(s)

结果如下:

--Congratulations---
~~~~~Congratulations
Congratulations*****

3.strip()方法

#strip()方法删的是两端的字符,删右端的字符用rstrip(),左端的用lstrip()。默认是空格,也可以指定参数。
s = "   \n\nHello world     \t"
t = s.strip()
print(t)

结果如下:

Hello world

4.split()方法:返回的是一个列表

s = "apple; peach; banana; pear"
print(s.split(";"))
s = "2014-10-31"
t = s.split("-")
print(t)
print(list(map(int, t)))

结果如下

['apple', ' peach', ' banana', ' pear']
['2014', '10', '31']
[2014, 10, 31]

5.lower()、upeer()、capitalize()、title()、swapcase()

s = "What is yOur Name?"
print(s.lower())  #全部转化为小写
print(s.upper())  #全部转化为大写
print(s.capitalize())  # 将字符串的首字符大写
print(s.title())   #将每个单词的首字母大写
print(s.swapcase())  #大小写互换
what is your name?
WHAT IS YOUR NAME?
What is your name?
What Is Your Name?
wHAT IS YoUR nAME?
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值