【Python】String

Posted by 西维蜀黍 on 2019-11-01, Last Modified on 2024-01-09

String 格式化

在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下:

>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'

你可能猜到了,%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

常见的占位符有:

占位符 替换内容
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数

访问字符或子字符串

Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。

Python 访问子字符串,可以使用方括号来截取字符串,如下实例:

#!/usr/bin/python
 
var1 = 'Hello World!'
var2 = "Python Runoob"
 
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

转义字符

在需要在字符中使用特殊字符时,python 用反斜杠 \ 转义字符。如下表:

转义字符 描述
(在行尾时) 续行符
\ 反斜杠符号
' 单引号
" 双引号
\a 响铃
\b 退格(Backspace)
\e 转义
\000
\n 换行
\v 纵向制表符
\t 横向制表符
\r 回车
\f 换页
\oyy 八进制数,yy代表的字符,例如:\o12代表换行
\xyy 十六进制数,yy代表的字符,例如:\x0a代表换行
\other 其它的字符以普通格式输出

字符串运算符

下表实例变量 a 值为字符串 “Hello”,b 变量值为 “Python”:

操作符 描述 实例
+ 字符串连接 »>a + b ‘HelloPython’
* 重复输出字符串 »>a * 2 ‘HelloHello’
[] 通过索引获取字符串中字符 »>a[1] ’e'
[ : ] 截取字符串中的一部分 »>a[1:4] ’ell'
in 成员运算符 - 如果字符串中包含给定的字符返回 True »>“H” in a True
not in 成员运算符 - 如果字符串中不包含给定的字符返回 True »>“M” not in a True
r/R 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母"r"(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 »>print r’\n’ \n »> print R’\n’ \n
% 格式字符串 请看下一章节
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
a = "Hello"
b = "Python"
 
print "a + b 输出结果:", a + b 
print "a * 2 输出结果:", a * 2 
print "a[1] 输出结果:", a[1] 
print "a[1:4] 输出结果:", a[1:4] 
 
if( "H" in a) :
    print "H 在变量 a 中" 
else :
    print "H 不在变量 a 中" 
 
if( "M" not in a) :
    print "M 不在变量 a 中" 
else :
    print "M 在变量 a 中"
 
print r'\n'
print R'\n'

Unicode 字符串

Python 中定义一个 Unicode 字符串和定义一个普通字符串一样简单:

>>> u'Hello World !'
u'Hello World !'

引号前小写的"u"表示这里创建的是一个 Unicode 字符串。如果你想加入一个特殊字符,可以使用 Python 的 Unicode-Escape 编码。如下例所示:

>>> u'Hello\u0020World !'
u'Hello World !'

被替换的 \u0020 标识表示在给定位置插入编码值为 0x0020 的 Unicode 字符(空格符)。

Immutability

In Python, strings are immutable. This means that once a string is created, it cannot be modified. Every time you perform an operation that seems to modify a string, what you’re actually doing is creating a new string. This is different from data types like lists, which can be modified in place.

Here’s a simple example to illustrate this:

pythonCopy code
a = "Hello"
print(id(a))  # This prints the memory address of the string "Hello"

# Now, let's try to modify it
a = a + " World"
print(id(a))  # This prints the memory address of the new string "Hello World"

In this example, when we modify a by appending " World" to it, Python creates a new string "Hello World" and updates a to reference this new string. The original string "Hello" remains unchanged in memory. This is why we see different memory addresses before and after the modification.


In another example, you can use that character in a variable assignment like shown in the example below.

# print h

greeting = "hi there!"
first = greeting[0]
print(first)

The variable first holds a string that just has the letter h. You cannot, however, do this assignment in the opposite direction. In other words, you cannot take a string, or a letter, and assign it to a particular index in another string. The program below would throw an error.

greeting = "hi there!"
greeting[0] = "H"
print(greeting)
Error: Line 2
TypeError: 'str' does not support item assignment on line 2

Benefits of Immutable Objects

  1. *Hashability and Dictionary Keys:* Immutable objects can be used as keys in dictionaries because their hash value remains constant, ensuring that the key-value mapping is consistent.
  2. *Memory Efficiency:* Since immutable objects cannot change their value, Python can optimize memory usage. Reusing the same immutable object across the program whenever possible reduces memory overhead.
  3. *Thread Safety:* Immutability provides inherent thread safety. When multiple threads access the same immutable object, there’s no risk of data corruption due to concurrent modifications.
  4. *Predictability and Debugging:* With immutability, you can be confident that a given object’s value will not change unexpectedly, leading to more predictable and easier-to-debug code.
  5. *Performance Optimization:* Immutable objects facilitate certain performance optimizations, such as caching hash values for quick dictionary lookups.

Reference