一、 字符串
1、改变字符串的大小写
name = "ada lovelace"
print(name)
print(name.title()) # 首字母大写的方式显示每单词
print(name.upper()) # 将字符串全部改成大写
print(name.lower()) # 将字符串全部改成小写
运行结果如下:
ada lovelace
Ada Lovelace
ADA LOVELACE
ada lovelace
2、 合并(拼接)字符串
使用“+”号实现拼接:
frist_name = "ada"
last_name = "lovelace"
full_name = frist_name + " " + last_name
print(full_name)
运行结果:
ada lovelace
3、删除空白
lstrip()【删除字符串开头的空白】
rstrip()【删除字符串结尾的空白】
strip()【删除字符串开头及结尾的空白】
但是 删除效果都是暂时的,要永久删除的话需要把删除后的值存回原来的变量值中
language = ' python '
print(language.rstrip())
print(language.lstrip())
print(language.strip())
运行结果:
‘ python’
‘python ’
‘python’
二、数字
注意在输出的时候 可以使用 str() 函数来避免类型错误
age = 23
message = "happy " + age +"rd birthday"
print(message)
运行结果:
message = "happy " + age +"rd birthday"
TypeError: Can't convert 'int' object to str implicitly
原因分析: “+”是用来实现字符串之间的拼接,但是age不是字符串是int类型变量,因此编译器出现了错误,因此我们需要将 age 转换成字符串类型
【修改后】
age = 23
message = "happy " + str(age) +"rd birthday"
print(message)
运行结果:
happy 23rd birthday
【python 之禅】输入 import this:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

本文详细介绍了Python中字符串的基本操作,包括大小写转换、拼接、去除空白等,同时讲解了数字处理技巧,如类型转换,确保代码的正确运行。此外,还分享了有趣的Python之禅,为读者提供编程哲学的启示。

被折叠的 条评论
为什么被折叠?



