栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python(5):字符串学习

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 = "   nnHello 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?
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/879669.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号