字符串是 Python 中的一种数据结构,表示一系列字符。它是一种不可变的数据类型,这意味着一旦创建了一个字符串,就无法更改它。字符串广泛用于许多不同的应用程序,例如存储和操作文本数据,表示名称、地址和其他可以表示为文本的数据类型。
例子:
"Geeksforgeeks" or 'Geeksforgeeks'
Python 没有字符数据类型,单个字符只是一个长度为 1 的字符串。方括号可用于访问字符串的元素。
print("A Computer Science portal for geeks")
输出:
A Computer Science portal for geeks
Python 中的字符串可以使用单引号或双引号甚至三引号创建。
# Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'm a Geek" print("\nString with the use of Double Quotes: ") print(String1) # Creating a String # with triple Quotes String1 = '''I'm a Geek and I live in a world of "Geeks"''' print("\nString with the use of Triple Quotes: ") print(String1) # Creating String with triple # Quotes allows multiple lines String1 = '''Geeks For Life''' print("\nCreating a multiline String: ") print(String1)
String with the use of Single Quotes: Welcome to the Geeks World String with the use of Double Quotes: I'm a Geek String with the use of Triple Quotes: I'm a Geek and I live in a world of "Geeks" Creating a multiline String: Geeks For Life
在Python中,可以使用 Indexing 方法访问 String 的各个字符。索引允许负地址引用访问字符串后面的字符,例如-1 指最后一个字符,-2 指倒数第二个字符,等等。
访问超出范围的索引将导致IndexError。只允许整数作为索引、浮点数或其他会导致TypeError 的类型传递。
# Python Program to Access # characters of String String1 = "GeeksForGeeks" print("Initial String: ") print(String1) # Printing First character print("\nFirst character of String is: ") print(String1[0]) # Printing Last character print("\nLast character of String is: ") print(String1[-1])
Initial String: GeeksForGeeks First character of String is: G Last cha racter of String is: s
通过访问字符串中的字符,我们还可以反转它们。我们可以通过写入 [::-1] 来反转字符串,字符串将被反转。
#Program to reverse a string gfg = "geeksforgeeks" print(gfg[::-1])
skeegrofskeeg
我们还可以使用内置的join和reversed函数来反转字符串。
# Program to reverse a string gfg = "geeksforgeeks" # Reverse the string using reversed and join function gfg = "".join(reversed(gfg)) print(gfg)
要访问 String 中的某个范围的字符,使用切片的方法。String 中的切片是通过使用切片运算符(冒号)完成的。
# Python Program to # demonstrate String slicing # Creating a String String1 = "GeeksForGeeks" print("Initial String: ") print(String1) # Printing 3rd to 12th character print("\nSlicing characters from 3-12: ") print(String1[3:12])
Initial String: GeeksForGeeks Slicing characters from 3-12: ksForGeek Slicing characters between 3rd and 2nd last character: ksForGee
在 Python 中,不允许更新或删除字符串中的字符。这将导致错误,因为不支持从字符串中分配项目或删除项目。尽管使用内置的 del 关键字可以删除整个字符串。这是因为字符串是不可变的,因此一旦分配了字符串的元素就不能更改。只能将新字符串重新分配给相同的名称。
# Python Program to Update # character of a String String1 = "Hello, I'm a Geek" print("Initial String: ") print(String1) # Updating a character of the String ## As python strings are immutable, they don't support item updation directly ### there are following two ways #1 list1 = list(String1) list1[2] = 'p' String2 = ''.join(list1) print("\nUpdating character at 2nd Index: ") print(String2) #2 String3 = String1[0:2] + 'p' + String1[3:] print(String3)
Initial String: Hello, I’m a Geek Updating character at 2nd Index: Heplo, I’m a Geek Heplo, I’m a Geek
Initial String: Hello, I’m a Geek
Updating character at 2nd Index: Heplo, I’m a Geek Heplo, I’m a Geek
# Python Program to Update # entire String String1 = "Hello, I'm a Geek" print("Initial String: ") print(String1) # Updating a String String1 = "Welcome to the Geek World" print("\nUpdated String: ") print(String1)
Initial String: Hello, I'm a Geek Updated String: Welcome to the Geek World
# Python Program to Delete # characters from a String String1 = "Hello, I'm a Geek" print("Initial String: ") print(String1) # Deleting a character # of the String String2 = String1[0:2] + String1[3:] print("\nDeleting character at 2nd Index: ") print(String2)
Initial String: Hello, I’m a Geek Deleting character at 2nd Index: Helo, I’m a Geek
Deleting character at 2nd Index: Helo, I’m a Geek
使用 del 关键字可以删除整个字符串。此外,如果我们尝试打印字符串,这将产生错误,因为字符串已被删除且无法打印。
# Python Program to Delete # entire String String1 = "Hello, I'm a Geek" print("Initial String: ") print(String1) # Deleting a String # with the use of del del String1 print("\nDeleting entire String: ") print(String1)
错误:
Traceback (most recent call last): File “/home/e4b8f2170f140da99d2fe57d9d8c6a94.py”, line 12, in print(String1) NameError: name ‘String1’ is not defined
在打印带有单引号和双引号的字符串时会导致SyntaxError,因为字符串已经包含单引号和双引号,因此无法使用其中任何一个打印。因此,要打印这样的字符串,要么使用三重引号,要么使用转义序列来打印这样的字符串。
转义序列以反斜杠开头,可以有不同的解释。如果使用单引号表示字符串,则字符串中出现的所有单引号都必须转义,双引号也是如此。
# Python Program for # Escape Sequencing # of String # Initial String String1 = '''I'm a "Geek"''' print("Initial String with use of Triple Quotes: ") print(String1) # Escaping Single Quote String1 = 'I\'m a "Geek"' print("\nEscaping Single Quote: ") print(String1) # Escaping Double Quotes String1 = "I'm a \"Geek\"" print("\nEscaping Double Quotes: ") print(String1) # Printing Paths with the # use of Escape Sequences String1 = "C:\\Python\\Geeks\\" print("\nEscaping Backslashes: ") print(String1) # Printing Paths with the # use of Tab String1 = "Hi\tGeeks" print("\nTab: ") print(String1) # Printing Paths with the # use of New Line String1 = "Python\nGeeks" print("\nNew Line: ") print(String1)
Initial String with use of Triple Quotes: I'm a "Geek" Escaping Single Quote: I'm a "Geek" Escaping Double Quotes: I'm a "Geek" Escaping Backslashes: C:\Python\Geeks\ Tab: Hi Geeks New Line: Python Geeks
要忽略字符串中的转义序列,请使用r或R ,这意味着该字符串是原始字符串,其中的转义序列将被忽略。
# Printing hello in octal String1 = "\110\145\154\154\157" print("\nPrinting in Octal with the use of Escape Sequences: ") print(String1) # Using raw String to # ignore Escape Sequences String1 = r"This is \110\145\154\154\157" print("\nPrinting Raw String in Octal Format: ") print(String1) # Printing Geeks in HEX String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58" print("\nPrinting in HEX with the use of Escape Sequences: ") print(String1) # Using raw String to # ignore Escape Sequences String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58" print("\nPrinting Raw String in HEX Format: ") print(String1)
Printing in Octal with the use of Escape Sequences: Hello Printing Raw String in Octal Format: This is \110\145\154\154\157 Printing in HEX with the use of Escape Sequences: This is Geeks in HEX Printing Raw String in HEX Format: This is \x47\x65\x65\x6b\x73 in \x48\x45\x58
Python 中的字符串可以使用format()方法进行格式化,这是一种非常通用且功能强大的字符串格式化工具。String 中的 Format 方法包含花括号 {} 作为占位符,可以根据位置或关键字保存参数以指定顺序。
# Python Program for # Formatting of Strings # Default order String1 = "{} {} {}".format('Geeks', 'For', 'Life') print("Print String in default order: ") print(String1) # Positional Formatting String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life') print("\nPrint String in Positional order: ") print(String1) # Keyword Formatting String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life') print("\nPrint String in order of Keywords: ") print(String1)
Print String in default order: Geeks For Life Print String in Positional order: For Geeks Life Print String in order of Keywords: Life For Geeks
二进制、十六进制等整数和浮点数可以四舍五入或使用格式说明符以指数形式显示。
# Formatting of Integers String1 = "{0:b}".format(16) print("\nBinary representation of 16 is ") print(String1) # Formatting of Floats String1 = "{0:e}".format(165.6458) print("\nExponent representation of 165.6458 is ") print(String1) # Rounding off Integers String1 = "{0:.2f}".format(1/6) print("\none-sixth is : ") print(String1)
Binary representation of 16 is 10000 Exponent representation of 165.6458 is 1.656458e+02 one-sixth is : 0.17
字符串可以左对齐()或居中(^),使用格式说明符对齐,由冒号(:)分隔。
# String alignment String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks', 'for', 'Geeks') print("\nLeft, center and right alignment with Formatting: ") print(String1) # To demonstrate aligning of spaces String1 = "\n{0:^16} was founded in {1:<4}!".format("GeeksforGeeks", 2009) print(String1)
Left, center and right alignment with Formatting: |Geeks | for | Geeks| GeeksforGeeks was founded in 2009 !
旧样式格式化是在不使用格式化方法的情况下通过使用%运算符 完成的
# Python Program for # Old Style Formatting # of Integers Integer1 = 12.3456789 print("Formatting in 3.2f format: ") print('The value of Integer1 is %3.2f' % Integer1) print("\nFormatting in 3.4f format: ") print('The value of Integer1 is %3.4f' % Integer1)
Formatting in 3.2f format: The value of Integer1 is 12.35 Formatting in 3.4f format: The value of Integer1 is 12.3457
原文链接:codingdict.net