python print 输出到txt_(Python基础教程之七)Python字符串操作
在Python中,string文字是:
- 代表Unicode字符的字節(jié)數(shù)組
- 用單引號或雙引號引起來
- 無限長度
字符串文字
str = 'hello world'str = "hello world"一個多行字符串使用三個單引號或三個雙引號創(chuàng)建的。
多行字符串文字
str = '''Say helloto pythonprogramming'''str = """Say helloto pythonprogramming"""Python沒有字符數(shù)據(jù)類型,單個字符就是長度為1的字符串。
2. Substring or slicing
通過使用slice語法,我們可以獲得一系列字符。索引從零開始。
str[m:n] 從位置2(包括)到5(不包括)返回字符串。
從索引2到5的子字符串
str = 'hello world'print(str[2:5]) # llo負(fù)切片將從末尾返回子字符串。
子串從索引-5到-2
str = 'hello world'print(str[-5:-2])?? # worstr[-m:-n] 將字符串從位置-5(不包括)返回到-2(包括)。3. Strings as arrays
在python中,字符串表現(xiàn)為數(shù)組。方括號可用于訪問字符串的元素。
字符在第n個位置
str = 'hello world'print(str[0])?? # hprint(str[1])?? # eprint(str[2])?? # lprint(str[20])? # IndexError: string index out of range4. String length
len()函數(shù)返回字符串的長度:
字符串長度
str = 'hello world'print(len(str)) # 115. String Formatting
要在python中格式化s字符串,請{ }在所需位置在字符串中使用占位符。將參數(shù)傳遞給format()函數(shù)以使用值格式化字符串。
我們可以在占位符中傳遞參數(shù)位置(從零開始)。
字符串格式()
age = 36name = 'Lokesh'txt = "My name is {} and my age is {}"print(txt.format(name, age))??? # My name is Lokesh and my age is 36txt = "My age is {1} and the name is {0}"print(txt.format(name, age))??? # My age is 36 and the name is Lokesh6. String Methods
6.1. capitalize()
它返回一個字符串,其中給定字符串的第一個字符被轉(zhuǎn)換為大寫。當(dāng)?shù)谝粋€字符為非字母時,它將返回相同的字符串。
字符串大寫()
name = 'lokesh gupta'print( name.capitalize() )? # Lokesh guptatxt = '38 yrs old lokesh gupta'print( txt.capitalize() )?? # 38 yrs old lokesh gupta6.2. casefold()
它返回一個字符串,其中所有字符均為給定字符串的小寫字母。
字符串casefold()
txt = 'My Name is Lokesh Gupta'print( txt.casefold() ) # my name is lokesh gupta6.3. center()
使用指定的字符(默認(rèn)為空格)作為填充字符,使字符串居中對齊。
在給定的示例中,輸出總共需要20個字符,而“ hello world”位于其中。
字符串中心
txt = "hello world"x = txt.center(20)print(x)??? # '??? hello world???? '6.4. count()
它返回指定值出現(xiàn)在字符串中的次數(shù)。它有兩種形式:
count(value) - value to search for in the string. count(value, start, end) - value to search for in the string, where search starts from start position till end position.字符串?dāng)?shù)()
txt = "hello world"print( txt.count("o") )???????? # 2print( txt.count("o", 4, 7) )?? # 16.5. encode()
它使用指定的編碼對字符串進行編碼。如果未指定編碼,UTF-8將使用。
字符串encode()
txt = "My name is ?mber"x = txt.encode()print(x)??? # b'My name is xc3xa5mber'6.6. endswith()
True如果字符串以指定值結(jié)尾,則返回,否則返回False。
字符串endswith()
txt = "hello world"print( txt.endswith("world") )????? # Trueprint( txt.endswith("planet") )???? # False6.7. expandtabs()
它將制表符大小設(shè)置為指定的空格數(shù)。
字符串expandtabs()
txt = "helloworld"print( txt.expandtabs(2) )????? # 'hello world'print( txt.expandtabs(4) )????? # 'hello?? world'print( txt.expandtabs(16) )???? # 'hello?????????? world'6.8. find()
它查找指定值的第一次出現(xiàn)。-1如果字符串中沒有指定的值,它將返回。
find()與index()方法相同,唯一的區(qū)別是,index()如果找不到該值,該方法將引發(fā)異常。
字符串find()
txt = "My name is Lokesh Gupta"x = txt.find("e")print(x)??????? # 66.9. format()
它格式化指定的字符串,并在字符串的占位符內(nèi)插入?yún)?shù)值。
字符串格式()
age = 36name = 'Lokesh'txt = "My name is {} and my age is {}"print( txt.format(name, age) )? # My name is Lokesh and my age is 366.10. format_map()
它用于返回字典鍵的值,以格式化帶有命名占位符的字符串。
字符串format_map()
params = {'name':'Lokesh Gupta', 'age':'38'}txt = "My name is {name} and age is {age}"x = txt.format_map(params)print(x)??????? # My name is Lokesh Gupta and age is 386.11. index()
- 它在給定的字符串中查找指定值的第一次出現(xiàn)。
- 如果找不到要搜索的值,則會引發(fā)異常。
字符串index()
txt = "My name is Lokesh Gupta"x = txt.index("e")print(x)??????? # 6x = txt.index("z")? # ValueError: substring not found6.12. isalnum()
它檢查字母數(shù)字字符串。True如果所有字符都是字母數(shù)字,即字母(a-zA-Z)和數(shù)字,它將返回(0-9)。
字符串isalnum()
print("LokeshGupta".isalnum())????? # Trueprint("Lokesh Gupta".isalnum())???? # False - Contains space6.13. isalpha()
True如果所有字符都是字母,則返回它,即字母(a-zA-Z)。
字符串isalpha()
print("LokeshGupta".isalpha())????????? # Trueprint("Lokesh Gupta".isalpha())???????? # False - Contains spaceprint("LokeshGupta38".isalpha())??????? # False - Contains numbers6.14. isdecimal()
如果所有字符均為小數(shù)(0-9),則返回代碼。否則返回False。
字符串isdecimal()
print("LokeshGupta".isdecimal())??? # Falseprint("12345".isdecimal())????????? # Trueprint("123.45".isdecimal())???????? # False - Contains 'point'print("1234 5678".isdecimal())????? # False - Contains space6.15. isdigit()
True如果所有字符都是數(shù)字,則返回,否則返回False。指數(shù)也被認(rèn)為是數(shù)字。
字符串isdigit()
print("LokeshGupta".isdigit())????? # Falseprint("12345".isdigit())??????????? # Trueprint("123.45".isdigit())?????????? # False - contains decimal pointprint("12342".isdigit())?????? # True - unicode for square 26.16. isidentifier()
True如果字符串是有效的標(biāo)識符,則返回,否則返回False。
有效的標(biāo)識符僅包含字母數(shù)字字母(a-z)和(0-9)或下劃線( _ )。它不能以數(shù)字開頭或包含任何空格。
字符串isidentifier()
print( "Lokesh_Gupta_38".isidentifier() )?????? # Trueprint( "38_Lokesh_Gupta".isidentifier() )?????? # False - Start with numberprint( "_Lokesh_Gupta".isidentifier() )???????? # Trueprint( "Lokesh Gupta 38".isidentifier() )?????? # False - Contain spaces6.17. islower()
True如果所有字符均小寫,則返回,否則返回False。不檢查數(shù)字,符號和空格,僅檢查字母字符。
字符串islower()
print( "LokeshGupta".islower() )??????? # Falseprint( "lokeshgupta".islower() )??????? # Trueprint( "lokesh_gupta".islower() )?????? # Trueprint( "lokesh_gupta_38".islower() )??? # True6.18. isnumeric()
True如果所有字符都是數(shù)字(0-9),則it方法返回,否則返回False。指數(shù)也被認(rèn)為是數(shù)值。
字符串isnumeric()
print("LokeshGupta".isnumeric())??? # Falseprint("12345".isnumeric())????????? # Trueprint("123.45".isnumeric())???????? # False - contains decimal pointprint("12342".isnumeric())???? # True - unicode for square 26.19. isprintable()
它返回True,如果所有字符都打印,否則返回False。不可打印字符用于指示某些格式化操作,例如:
- 空白(被視為不可見的圖形)
- 回車
- 標(biāo)簽
- 換行
- 分頁符
- 空字符
字符串isprintable()
print("LokeshGupta".isprintable())????? # Trueprint("Lokesh Gupta".isprintable())???? # Trueprint("LokeshGupta".isprintable())??? # False6.20. isspace()
True如果字符串中的所有字符都是空格,則返回,否則返回False。
6.21. istitle()
它返回True如果文本的所有單詞以大寫字母開頭,字的其余均為小寫字母,即標(biāo)題案例。否則False。
字符串istitle()
print("Lokesh Gupta".istitle())???? # Trueprint("Lokesh gupta".istitle())???? # False6.22. isupper()
True如果所有字符均大寫,則返回,否則返回False。不檢查數(shù)字,符號和空格,僅檢查字母字符。
字符串isupper()
print("LOKESHGUPTA".isupper())????? # Trueprint("LOKESH GUPTA".isupper())???? # Trueprint("Lokesh Gupta".isupper())???? # False6.23. join()
它以可迭代方式獲取所有項目,并使用強制性指定的分隔符將它們連接為一個字符串。
字符串join()
myTuple = ("Lokesh", "Gupta", "38")x = "#".join(myTuple)print(x)??? # Lokesh#Gupta#386.24. ljust()
此方法將使用指定的字符(默認(rèn)為空格)作為填充字符使字符串左對齊。
字符串ljust()
txt = "lokesh"x = txt.ljust(20, "-")print(x)??? # lokesh--------------6.25. lower()
它返回一個字符串,其中所有字符均為小寫。符號和數(shù)字將被忽略。
字符串lower()
txt = "Lokesh Gupta"x = txt.lower()print(x)??? # lokesh gupta6.26. lstrip()
它刪除所有前導(dǎo)字符(默認(rèn)為空格)。
字符串lstrip()
txt = "#Lokesh Gupta"x = txt.lstrip("#_,.")print(x)??? # Lokesh Gupta6.27. maketrans()
它創(chuàng)建一個字符到其轉(zhuǎn)換/替換的一對一映射。當(dāng)在translate()方法中使用時,此翻譯映射隨后用于將字符替換為其映射的字符。
字符串maketrans()
dict = {"a": "123", "b": "456", "c": "789"}string = "abc"print(string.maketrans(dict))?? # {97: '123', 98: '456', 99: '789'}6.28. partition()
它在給定的文本中搜索指定的字符串,并將該字符串拆分為包含三個元素的元組:
- 第一個元素包含指定字符串之前的部分。
- 第二個元素包含指定的字符串。
- 第三個元素包含字符串后面的部分。
字符串partition()
txt = "my name is lokesh gupta"x = txt.partition("lokesh")print(x)??? # ('my name is ', 'lokesh', ' gupta')print(x[0]) # my name isprint(x[1]) # lokeshprint(x[2]) #? gupta6.29. replace()
它將指定的短語替換為另一個指定的短語。它有兩種形式:
- string.replace(oldvalue, newvalue)
- string.replace(oldvalue, newvalue, count)–“計數(shù)”指定要替換的出現(xiàn)次數(shù)。默認(rèn)為所有事件。
字符串replace()
txt = "A A A A A"x = txt.replace("A", "B")print(x)??? # B B B B Bx = txt.replace("A", "B", 2)print(x)??? # B B A A A6.30. rfind()
它查找指定值的最后一次出現(xiàn)。-1如果在給定的文本中找不到該值,則返回該值。
字符串rfind()
txt = "my name is lokesh gupta"x = txt.rfind("lokesh")????print(x)??????? # 11x = txt.rfind("amit")??????print(x)??????? # -16.31. rindex()
它查找指定值的最后一次出現(xiàn),如果找不到該值,則引發(fā)異常。
字符串rindex()
txt = "my name is lokesh gupta"x = txt.rindex("lokesh")???????print(x)??????????????? # 11x = txt.rindex("amit")? # ValueError: substring not found6.32. rjust()
它將使用指定的字符(默認(rèn)為空格)作為填充字符來右對齊字符串。
字符串rjust()
txt = "lokesh"x = txt.rjust(20,"#")print(x, "is my name")? # ##############lokesh is my name6.33. rpartition()
它搜索指定字符串的最后一次出現(xiàn),并將該字符串拆分為包含三個元素的元組。
- 第一個元素包含指定字符串之前的部分。
- 第二個元素包含指定的字符串。
- 第三個元素包含字符串后面的部分。
字符串rpartition()
txt = "my name is lokesh gupta"x = txt.rpartition("lokesh")print(x)??? # ('my name is ', 'lokesh', ' gupta')print(x[0]) # my name isprint(x[1]) # lokeshprint(x[2]) #? gupta6.34. rsplit()
它將字符串從右開始拆分為一個列表。
字符串rsplit()
txt = "apple, banana, cherry"x = txt.rsplit(", ")print(x)??? # ['apple', 'banana', 'cherry']6.35. rstrip()
它刪除所有結(jié)尾字符(字符串末尾的字符),空格是默認(rèn)的結(jié)尾字符。
字符串rstrip()
txt = "???? lokesh???? "x = txt.rstrip()print(x)??? # '???? lokesh'6.36. split()
它將字符串拆分為列表。您可以指定分隔符。默認(rèn)分隔符為空格。
字符串split()
txt = "my name is lokesh"x = txt.split()print(x)??? # ['my', 'name', 'is', 'lokesh']6.37. splitlines()
通過在換行符處進行拆分,它將字符串拆分為列表。
字符串splitlines()
txt = "my nameis lokesh"x = txt.splitlines()print(x)??? # ['my name', 'is lokesh']6.38. startswith()
True如果字符串以指定值開頭,則返回,否則返回False。字符串比較區(qū)分大小寫。
字符串startswith()
txt = "my name is lokesh"print( txt.startswith("my") )?? # Trueprint( txt.startswith("My") )?? # False6.39. strip()
它將刪除所有前導(dǎo)(開頭的空格)和結(jié)尾(結(jié)尾的空格)字符(默認(rèn)為空格)。
字符串strip()
txt = "?? my name is lokesh?? "print( txt.strip() )??? # 'my name is lokesh'6.40. swapcase()
它返回一個字符串,其中所有大寫字母均為小寫字母,反之亦然。
字符串swapcase()
txt = "My Name Is Lokesh Gupta"print( txt.swapcase() ) # mY nAME iS lOKESH gUPTA6.41. title()
它返回一個字符串,其中每個單詞的第一個字符均為大寫。如果單詞開頭包含數(shù)字或符號,則其后的第一個字母將轉(zhuǎn)換為大寫字母。
字符串標(biāo)題()
print( "lokesh gupta".title() ) # Lokesh Guptaprint( "38lokesh gupta".title() )?? # 38Lokesh Guptaprint( "1. lokesh gupta".title() )? # Lokesh Gupta6.42. translate()
它需要轉(zhuǎn)換表來根據(jù)映射表替換/翻譯給定字符串中的字符。
字符串translate()
translation = {97: None, 98: None, 99: 105}string = "abcdef"??print( string.translate(translation) )? # idef6.43. upper()
它返回一個字符串,其中所有字符均為大寫。符號和數(shù)字將被忽略。
字符串upper()
txt = "lokesh gupta"print( txt.upper() )??? # LOKESH GUPTA6.44. zfill()
它在字符串的開頭添加零(0),直到達(dá)到指定的長度。
字符串zfill()
txt = "100"x = txt.zfill(10)print( 0000000100 ) # 0000000100學(xué)習(xí)愉快!
作者:分布式編程 出處:https://zthinker.com/ 如果你喜歡本文,請長按二維碼,關(guān)注 分布式編程 .
總結(jié)
以上是生活随笔為你收集整理的python print 输出到txt_(Python基础教程之七)Python字符串操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring aop实现原理_Sprin
- 下一篇: Hibernate_2_Hibernat