📜  Python字符串

📅  最后修改于: 2022-05-13 01:55:39.666000             🧑  作者: Mango

Python字符串

在Python中,字符串是表示 Unicode字符的字节数组。但是, Python没有字符数据类型,单个字符只是长度为 1 的字符串。方括号可用于访问字符串的元素。

创建字符串

Python中的字符串可以使用单引号或双引号甚至三引号来创建。

Python3
# 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)


Python3
# 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])


Python3
# 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])
 
# Printing characters between
# 3rd and 2nd last character
print("\nSlicing characters between " +
    "3rd and 2nd last character: ")
print(String1[3:-2])


Python3
# 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
String1[2] = 'p'
print("\nUpdating character at 2nd Index: ")
print(String1)


Python3
# 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)


Python3
# 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
del String1[2]
print("\nDeleting character at 2nd Index: ")
print(String1)


Python3
# 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)


Python3
# 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)


Python3
# 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)


Python3
# 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)


Python3
# 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)


Python3
# 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)


Python3
# 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)


输出:

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中访问字符

在Python中,可以使用 Indexing 方法访问 String 的各个字符。索引允许负地址引用从字符串后面访问字符,例如 -1 表示最后一个字符,-2 表示倒数第二个字符,依此类推。

访问超出范围的索引将导致IndexError 。仅允许将整数作为索引、浮点数或其他会导致TypeError的类型传递。

字符串

Python3

# 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 character of String is: 
s

字符串切片

要访问字符串中的一系列字符,可以使用切片方法。通过使用切片运算符(冒号)对字符串进行切片。

Python3

# 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])
 
# Printing characters between
# 3rd and 2nd last character
print("\nSlicing characters between " +
    "3rd and 2nd last character: ")
print(String1[3:-2])

输出:

Initial String: 
GeeksForGeeks

Slicing characters from 3-12: 
ksForGeek

Slicing characters between 3rd and 2nd last character: 
ksForGee

从字符串中删除/更新

在Python中,不允许更新或删除字符串中的字符。这将导致错误,因为不支持从字符串中分配项目或删除项目。尽管使用内置的 del 关键字可以删除整个字符串。这是因为字符串是不可变的,因此字符串的元素一旦被分配就不能更改。只有新字符串可以重新分配给相同的名称。

字符更新:

Python3

# 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
String1[2] = 'p'
print("\nUpdating character at 2nd Index: ")
print(String1)

错误:

更新整个字符串:

Python3

# 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 

删除一个字符:

Python3

# 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
del String1[2]
print("\nDeleting character at 2nd Index: ")
print(String1)

错误:

删除整个字符串:

使用 del 关键字可以删除整个字符串。此外,如果我们尝试打印字符串,这将产生错误,因为 String 被删除并且无法打印。

Python3

# 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)

错误:

Python中的转义序列

在打印带有单引号和双引号的字符串时,会导致SyntaxError ,因为字符串已经包含单引号和双引号,因此无法使用其中任何一个来打印。因此,要打印这样的字符串,要么使用三引号,要么使用转义序列来打印这样的字符串。

转义序列以反斜杠开头,可以有不同的解释。如果使用单引号表示字符串,则字符串中存在的所有单引号都必须转义,双引号也是如此。

Python3

# 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)

输出:

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\

要忽略字符串中的转义序列,使用rR ,这意味着该字符串是原始字符串,并且其中的转义序列将被忽略。

Python3

# 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 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 方法包含花括号 {} 作为占位符,可以根据位置或关键字保存参数以指定顺序。

Python3

# 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

二进制、十六进制等整数和浮点数可以使用格式说明符进行四舍五入或以指数形式显示。

Python3

# 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

字符串可以使用格式说明符左对齐或居中对齐(^),用冒号(:)分隔。

Python3

# 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 !

旧样式格式化是通过使用%运算符而不使用格式方法完成的

Python3

# 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

有用的字符串操作

  • 字符串上的逻辑运算符
  • 使用 % 格式化字符串
  • 字符串模板类
  • 拆分字符串
  • Python文档字符串
  • 字符串切片
  • 查找字符串中的所有重复字符
  • Python中的反转字符串(5种不同的方式)
  • 用于检查字符串是否为回文的Python程序

字符串常量

Built-In FunctionDescription
string.ascii_lettersConcatenation of the ascii_lowercase and ascii_uppercase constants.
string.ascii_lowercaseConcatenation of lowercase letters
string.ascii_uppercaseConcatenation of uppercase letters
string.digitsDigit in strings
string.hexdigitsHexadigit in strings
string.lettersconcatenation of the strings lowercase and uppercase
string.lowercaseA string must contain lowercase letters.
string.octdigitsOctadigit in a string
string.punctuationASCII characters having punctuation characters.
string.printableString of characters which are printable
String.endswith()Returns True if a string ends with the given suffix otherwise returns False
String.startswith()Returns True if a string starts with the given prefix otherwise returns False
String.isdigit()Returns “True” if all characters in the string are digits, Otherwise, It returns “False”.
String.isalpha()Returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”.
string.isdecimal()Returns true if all characters in a string are decimal.
str.format()one of the string formatting methods in Python3, which allows multiple substitutions and value formatting.
String.indexReturns the position of the first occurrence of substring in a string
string.uppercaseA string must contain uppercase letters.
string.whitespaceA string containing all characters that are considered whitespace.
string.swapcase()Method converts all uppercase characters to lowercase and vice versa of the given string, and returns it
replace()returns a copy of the string where all occurrences of a substring is replaced with another substring.

不推荐使用的字符串函数

Built-In FunctionDescription
string.IsdecimalReturns true if all characters in a string are decimal
String.IsalnumReturns true if all the characters in a given string are alphanumeric.
string.IstitleReturns True if the string is a title cased string
String.partitionsplits the string at the first occurrence of the separator and returns a tuple.
String.IsidentifierCheck whether a string is a valid identifier or not.
String.lenReturns the length of the string.
String.rindexReturns the highest index of the substring inside the string if substring is found.
String.MaxReturns the highest alphabetical character in a string.
String.minReturns the minimum alphabetical character in a string.
String.splitlinesReturns a list of lines in the string.
string.capitalizeReturn a word with its first character capitalized.
string.expandtabsExpand tabs in a string replacing them by one or more spaces
string.findReturn the lowest indexing a sub string.
string.rfindfind the highest index.
string.countReturn the number of (non-overlapping) occurrences of substring sub in string
string.lowerReturn a copy of s, but with upper case, letters converted to lower case.
string.splitReturn a list of the words of the string, If the optional second argument sep is absent or None
string.rsplit()Return a list of the words of the string s, scanning s from the end.
rpartition()Method splits the given string into three parts
string.splitfieldsReturn a list of the words of the string when only used with two arguments.
string.joinConcatenate a list or tuple of words with intervening occurrences of sep.
string.strip()It returns a copy of the string with both leading and trailing white spaces removed
string.lstripReturn a copy of the string with leading white spaces removed.
string.rstripReturn a copy of the string with trailing white spaces removed.
string.swapcaseConverts lower case letters to upper case and vice versa.
string.translateTranslate the characters using table
string.upperlower case letters converted to upper case.
string.ljustleft-justify in a field of given width.
string.rjustRight-justify in a field of given width.
string.center()Center-justify in a field of given width.
string-zfillPad a numeric string on the left with zero digits until the given width is reached.
string.replaceReturn a copy of string s with all occurrences of substring old replaced by new.
string.casefold()Returns the string in lowercase which can be used for caseless comparisons.
string.encodeEncodes the string into any encoding supported by Python. The default encoding is utf-8.
string.maketransReturns a translation table usable for str.translate()

最近关于Python字符串的文章

https://youtu.be/mvDQuegHVXg

Python字符串程序

  • 弦乐 – 第 1 组,第 2 组
  • 字符串方法 – Set 1 , Set 2 , Set 3
  • 正则表达式(搜索、匹配和查找全部)
  • Python字符串标题方法
  • 交换字符串中的逗号和点
  • 将字符串转换为列表的程序
  • 计算并显示字符串中的元音
  • 用于检查密码有效性的Python程序
  • Python程序使用给定字符串中的集合来计算元音的数量
  • 检查字符串中的 URL
  • 检查给定字符串中是否存在子字符串
  • 检查两个字符串是否是字谜
  • 在Python中映射函数和字典以求和 ASCII 值
  • 在Python中映射函数和 Lambda 表达式以替换字符
  • Python中的SequenceMatcher用于最长公共子串
  • 用完整的姓氏打印姓名的首字母
  • Python中数据集中最常用的k个单词
  • 从列表中查找输入字符串的所有紧密匹配项
  • 检查一个二进制数中是否有K个连续的1
  • Python中的 Lambda 和过滤器
  • Python中具有不常见字符的连接字符串
  • 检查字符串的两半是否在Python中具有相同的字符集
  • 在Python中查找字符串中第一个重复的单词
  • Python中序列中重复次数第二多的单词
  • Python中的第K个不重复字符
  • 在Python中反转给定字符串中的单词
  • 在Python中用逗号打印数字作为1000个分隔符
  • 在Python中使用 pytrie 模块进行前缀匹配
  • Python正则表达式从字符串中提取最大数值
  • 两组成对的完整字符串
  • 从给定的句子中删除所有重复的单词
  • 按升序对句子中的单词进行排序
  • 反转句子中的每个单词
  • Python代码按字母顺序打印两个字符串的常见字符
  • 用于拆分和连接字符串的Python程序
  • Python代码在单次遍历中将空格移动到字符串的前面
  • Python中的运行长度编码
  • 从Python中的给定字符串中删除所有重复项
  • 在Python中增加字符的方法
  • 在Python中使用 pytrie 模块进行前缀匹配
  • 在Python中用逗号打印数字作为1000个分隔符
  • 在Python中反转给定字符串中的单词
  • 在Python中执行一串代码
  • Python中的字符串切片以检查字符串是否可以通过递归删除变为空
  • 在Python中打印转义字符的方法
  • Python中的字符串切片以旋转字符串
  • 计算字符串中某个单词的出现次数
  • 在Python中从数据集中找到k个最频繁的单词
  • Python|用完整的姓氏打印姓名的首字母
  • Python中的 Zip函数更改为新字符集
  • Python String isumeric() 及其应用
  • 在Python中按字典顺序对单词进行排序
  • 使用 Lambda 表达式和 reduce函数查找出现奇数次的数字
  • Python字符串标题方法
  • 按升序对句子中的单词进行排序
  • 将字符列表转换为字符串
  • Python groupby 方法删除所有连续重复
  • Python groupby 方法删除所有连续重复
  • 用于从字符串中删除第 i 个字符的Python程序
  • 在Python中用数字替换字符串以进行数据分析
  • Python中的格式化字符串字面量(f-strings)
  • Python文档字符串
  • 使用内置函数排列给定字符串
  • 在Python中查找字符串中每个单词的频率
  • 接受包含所有元音的字符串的程序
  • 计算一对字符串中匹配字符的数量
  • 计算给定字符串中频率最高的所有前缀
  • 检查字符串是否包含任何特殊字符的程序
  • 生成随机字符串,直到生成给定的字符串
  • Python程序在不使用内置函数的情况下计算大小写字符