美文网首页
Python 字符串3

Python 字符串3

作者: SateZheng | 来源:发表于2016-12-15 17:15 被阅读32次

字符串格式化输出

占位符

>>> "I like %s" % "python"
'I like python'
>>> "I like %s" % "Pascal"
'I like Pascal'

常用的有%s%d,或者再加上%f


新的格式化方法(string.format())

>>> s1 = "I like {0} {1}".format("python",2016)
>>> print s1
I like python 2016

这是 python 非常提倡的string.format()的格式化方法,其中{索引值}为占位符

也可以直接指定,如:

>>> s1 = "I like {name} {num},{num}".format(name="python",num=2016)
>>> print s1
I like python 2016,2016

字典格式化,如:

>>> lang = "python"
>>> print "I love %(program)s"%{"program":lang}
I love python

常用的字符串方法

分割字符串 split

将字符串根据某个分隔符分割,获得一个列表

>>> str = "I love python"
>>> str.split(" ")
['I', 'love', 'python']

拼接字符串 join

可以将列表中的字符串拼接成一个

>>> list
['I', 'love', 'python']
>>> " ".join(list)
'I love python'
>>> ",".join(list)
'I,love,python'

去掉字符串两头的空格 strip()

经常用在用户登录或者输入一些信息时,去除输入内容左右两边的空格

>>> str = " hello "
>>> str.strip()
'hello'
>>> str
' hello '
>>> str.lstrip()    # 去除左边的空格
'hello '
>>> str.rstrip()    # 去除右边的空格
' hello'

字符大小写的转换

在python中有下面一堆内建函数,用来实现各种类型的大小写转化

  • S.upper() # S中的字母大写
  • S.lower() # S中的字母小写
  • S.capitalize() # 首字母大写
  • S.title() # 将字符换首字母都变为大写
  • S.isupper() # S中的字母是否全是大写
  • S.islower() # S中的字母是否全是小写
  • S.istitle() # S中字符串中所有的单词拼写首字母是否为大写,且其他字母为小写

相关文章

  • Python3字符串处理函数

    Python3字符串处理函数 Python3

  • python重要概念

    1.python2和python3的区别 python3中的bytes,就是python3中的字符串python3...

  • 字符串操作方法

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • python字符串相关函数

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • 2018-09-28自学习资料

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • 字符串内置函数

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • 2018-07-18 字符串资料(函数方法)

    Python3字符串资料 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,...

  • day4 字符串自主操作

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • Day3-整理

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

  • day4-总结

    Python3字符串 Python访问字符串中的值 Python中的字符串用单引号(')或双引号(")括起来,同时...

网友评论

      本文标题:Python 字符串3

      本文链接:https://www.haomeiwen.com/subject/hvjgmttx.html