Type "copyright", "credits" or "license()" for more information.
>>> s = 'Python is cool' #1 创建字符串,单引号,双引号皆可
>>> words = s.split() #2 用空白符把字符串分隔到列表里去。string --> list
>>> words
['Python', 'is', 'cool']
>>> ' '.join(words) #3 是#2的逆操作。把子串列表组合成一字字符串并以空格分隔。list --> string
'Python is cool'
>>> '::'.join(words) #4 一对冒号分隔
'Python::is::cool'
>>> ''.join(words) #5 没有分隔符。将所有子串合并在一起。
'Pythoniscool'
>>> s.upper() #6 创建新字符串,在原有版本上全部大写。
'PYTHON IS COOL'
>>> s.upper().isupper() #串联用法
True
>>> s.title() #每个单词的首字母大写
'Python Is Cool'
>>> s.capitalize() #只大写第一个单词的开头,其他部分小写
'Python is cool'
>>> s.count('o') #计算子串'o'在字符串里出理的次数
3
>>> s.find('th') #找出子串'th'在字符串中的起始下标(索引值为2)
2
>>> s.find('xxoo') #没有找到匹配,则返回 -1
-1
>>> s.startswith('Python') #检查字符串是不是以给定子串开头。另外可参考 endswith方法
True
>>> s.replace('Python', 'Django') #简单的查找替换
'Django is cool'
>>>
>>> ss = ' python is cool '
>>> ss.strip() #移除行首行尾的空白字符。另可参考,rstrip() 、lstrip() 方法
python is cool
========================================================
善用 help 和 dir 方法
help(str)
dir(str)
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
>>> help(str.split)
Help on method_descriptor:
split(...)
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
>>> print str.split.__doc__
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
>>>