前面簡單介紹了Python基本運算,這里再來簡單講述一下Python字符串相關操作
>>> "www.jb51.net" #字符串使用單引號(')或雙引號(")表示'www.jb51.net'>>> 'www.jb51.net''www.jb51.net'>>> "www."+"jb51"+".net" #字符串可以用“+”號連接'www.jb51.net'>>> "#"*10 #字符串可以使用“*”來代表重復次數'##########'>>> "What's your name?" #單引號中可以直接使用雙引號,同理雙引號中也可以直接使用單引號"What's your name?">>> path = r"C:/newfile" #此處r開頭表示原始字符串,里面放置的內容都是原樣輸出>>> print(path)C:/newfile
>>> str1 = "python test">>> "test" in str1 #這里in用來判斷元素是否在序列中True>>> len(str1) #這里len()函數求字符串長度11>>> max(str1)'y'>>> min(str1)' '
>>> "I like %s" % "python" #使用%進行格式化輸出的經典表示方式'I like python'>>> dir(str) #列出字符串所有屬性與方法['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
format(*args,**kwargs)
采用*args賦值>>> str = "I like {1} and {2}" #這里{1}表示占位符(注意:這里得從{0}開始)>>> str.format("python","PHP")Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> str.format("python","PHP")IndexError: tuple index out of range>>> str = "I like {0} and {1}">>> str.format("python","PHP")'I like python and PHP'>>> "I like {1} and {0}".format("python","PHP")'I like PHP and python'>>> "I like {0:20} and {1:>20}".format("python","PHP")#{0:20}表示第一個位置占據20個字符,并且左對齊。{1:>20}表示第二個位置占據20個字符,且右對齊'I like python and PHP'>>> "I like {0:.2} and {1:^10.2}".format("python","PHP")#{0:.2}表示第一個位置截取2個字符,左對齊。{1:^10.2}表示第二個位置占據10個字符,且截取2個字符,^表示居中'I like py and PH '>>> "age: {0:4d} height: {1:6.2f}".format("32","178.55") #這里應該是數字,不能用引號,否則會被當作字符串而報錯!Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> "age: {0:4d} height: {1:6.2f}".format("32","178.55")ValueError: Unknown format code 'd' for object of type 'str'>>> "age: {0:4d} height: {1:8.2f}".format(32,178.5523154) #這里4d表示長度為4個字符的整數,右對齊。8.2f表示長度為8,保留2位小數的浮點數,右對齊。'age: 32 height: 178.55'
新聞熱點
疑難解答