[python教程入门学习]1.2 字符串

字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中引号包括单引号和双引号。这种灵活性能够在字符串中包含引号和撇号,如:

>>> str = "I'm David"
>>> str1 = 'I told my friend,"i love Python"'

常用字符串操作方法

以首字母大写的方式显示每个单词:

>>> name = "hello python world"
>>> print(name.title())
Hello Python World

将字符串改为全部大写或全部小写:

>>> str1 = "I love python"
>>> print(str1.upper())  #将字符串改为全部大写
I LOVE PYTHON >>> print(str1.lower())   #将字符串改为全部小写
i love python

字符串合拼(拼接)
最后,如果你的时间不是很紧张,并且又想快速的提高,最重要的是不怕吃苦,建议你可以价位@762459510 ,那个真的很不错,很多人进步都很快,需要你不怕吃苦哦!大家可以去添加上看一下~
Python使用加号(+)来合拼字符串,如:

>>> first_name = "Guido"
>>> last_name = "van Rossum"
>>> full_name = first_name + " " + last_name >>> print(full_name)
Guido van Rossum

使用制表符 或换行符
添加空白:

>>> print("Languages:
	Python
	C++
	PHP")
Languages:
    Python
    C++ PHP

删除字符串的空格:

>>> name = " p y t h o n "
>>> print(name.rstrip()) #删除字符串右端空格
 p y t h o n >>> print(name.lstrip())  #删除字符串左端空格
p y t h o n >>> print(name.strip())   #删除字符串两端空格
p y t h o n >>> print(name.replace(' ',''))  #删除字符串全部空格包括制表符和换行符
python

字符串的序号

字符串是字符的序列,可以按照单个字符或字符片段进行索引。

>>> name = "Hello World"
>>> print(name[0])
H >>> print(name[0:-1])
Hello Worl >>> print(name[-1])
d >>> print(name[::])
Hello World >>> print(name[0:11])
Hello World

找到字符串中最低字符索引号:S.find(sub [,start [,end]]) -> int

福利:私信回复【01】可免费获取python入门教程视频
失败时返回-1

>>> name = "hello world"
>>> print(name.find('d')) 10

返回某些字符出现的次数:S.count(sub[, start[, end]]) -> int

>>> name = "hello world"
>>> print(name.count('l')) 3

把字符串由分隔符返回一个列表:S.split([sep [,maxsplit]]) -> list of strings,如果给定maxsplit,则最多为maxsplit

>>> name = "hello world"
>>> print(name.split(' '))
['hello', 'world']
>>> print(name.split(' ',0))
['hello world']

字符串格式化输出(format和%用法)

%方法格式代码

>>> "{}:计算机{}的CPU占用率为{}%".format('2019-03-25','python',10)  #S.format(*args, **kwargs) -> string
'2019-03-25:计算机python的CPU占用率为10%'
>>> "%s:计算机%s的CPU占用率为%d%%" % ('2019-03-25','python',10)   #%用法
'2019-03-25:计算机python的CPU占用率为10%

小结:可以用help函数查看字符串的相关操作,比如help(str.find)

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容