一、python基础之字符串的处理

时间:2023-03-09 05:55:25
一、python基础之字符串的处理

最近开始重新回过头来巩固一下python的基础知识,并在此做一些记录以便未来更好的回顾

一、字符串的大小写转换

title()

使用title()方法可以将字符串中每个单词的首字母大写

 name = "hello world"
print(name.title())

运行得到结果:

Hello World

upper()

使用upper()方法可以将字符串中的每一个字母转换为大写

 name = "hello world"
print(name.upper())

运行得到结果:

HELLO WORLD

lower()

使用lower()方法可以将字符串中的所有字母转换为小写

 name = "HELLO WORLD"
print(name.lower())

运行得到结果:

hello world

二、拼接字符串

使用+对字符串进行拼接

 first = "hello"
last = "world"
add = first + " " + last
print(add)

运行后得到结果:

hello world

三、使用制表符和换行符

制表符

制表符可以使用字符组合\t

 print("\tpython")

运行得到结果:

#输出结果前有一个空格
python

换行符

 print("languages:\nPython\nJava")

运行得到结果:

languages:
Python
Java

四、删除空白

删除末尾的空白

使用rstrip()

 name = "python "
print(name.rstrip())

运行得到结果:

python

删除开头的空格

使用lstrip()

 name = " python"
print(name.lstrip())

运行得到结果:

python

同时剔除开头和结尾的空格

使用strip()

 name = " python "
print(name.strip())

运行得到结果:

python