关于Python |集1中字符串的有趣事实

1.字符串是不可变的 一旦定义了字符串,就不能对其进行更改。

null

# Python3 program to show that
# string cannot be changed
a = 'Geeks'
# output is displayed
print (a)
a[ 2 ] = 'E'
print (a) # causes error


输出:

Traceback (most recent call last):
  File "/home/adda662df52071c1e472261a1249d4a1.py", line 9, in 
    a[2] = 'E'
TypeError: 'str' object does not support item assignment

但下面的代码很好用。

# Python3 program to show that
# a string can be appended to a string.
a = 'Geeks'
# output is displayed
print (a)
a = a + 'for'
print (a) # works fine


输出:

Geeks
Geeksfor

在第二个程序中,解释器复制原始字符串,然后处理并修改它。所以这个表达 a=a+“代表” 不更改字符串,但重新分配变量 A. 添加到结果生成的新字符串,并下拉上一个字符串。

理解使用 id() 作用 函数用于返回对象的标识。

# Python3 program to show that
# both string hold same identity
string1 = "Hello"
string2 = "Hello"
print ( id (string1))
print ( id (string2))


输出:

93226944
93226944

string1和string2都指向相同的对象或相同的位置。现在,如果有人试图修改任何一个字符串,结果都会不同。

# Modifying a string
string1 = "Hello"
# identity of string1
print ( id (string1))
string1 + = "World"
print (string1)
# identity of modified string1
print ( id (string1))


输出:

93226944
'HelloWorld'
93326432

String1被修改,这与字符串是不可变的这一事实相矛盾,但修改前后的标识不同。这意味着string1的一个新对象是在修改后创建的,该修改确认了字符串是不可变的,因为string1的前一个对象没有更改,而是创建了一个新对象。

2.创建字符串的三种方法: Python中的字符串可以使用单引号、双引号或三引号创建。

单引号和双引号对字符串创建的作用相同。说到三重引号,当我们必须在多行中写入一个字符串并按原样打印而不使用任何转义序列时,就会用到三重引号。

# Python3 program to create
# strings in three different
# ways and concatenate them.
# string with single quotes
a = 'Geeks'
# string with double quotes
b = "for"
# string with triple quotes
c = '''Geeks a portal
for geeks'''
d = '''He said, "I'm fine."'''
print (a)
print (b)
print (c)
print (d)
# Concatenation of strings created
# using different quotes
print (a + b + c)


输出:

Geeks
for
Geeks a portal 
for geeks
He said, "I'm fine."
GeeksforGeeks a portal 
for geeks

如何在屏幕上打印单引号或双引号? 我们可以通过以下两种方式实现:

  • 第一种是使用转义字符显示附加引号。
  • 第二种方法是使用混合引号,即当我们想要打印单引号时,然后使用双引号作为分隔符,反之亦然。

范例-

print ( "Hi Mr Geek." )
# use of escape sequence
print ( "He said, "Welcome to GeeksforGeeks"" )
print ( 'Hey so happy to be here' )
# use of mix quotes
print ( 'Getting Geeky, "Loving it"' )


输出:

Hi Mr Geek.
He said, "Welcome to GeeksforGeeks"
Hey so happy to be here
Getting Geeky, "Loving it"

如何打印转义字符?

如果需要打印转义字符(),那么如果用户在字符串解释器中提到它,解释器会认为它是转义字符,不会打印它。为了打印转义字符,用户必须在打印前使用转义字符 ‘’ 如示例所示。

# Print Escape character
print ( " \ is back slash " )


输出:

  is back slash

本文由 阿比特·阿加瓦尔 .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇文章,并将文章邮寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享