在Python 3 中使用字符串
在Python中,字符序列称为字符串。它在Python中用于记录文本信息,例如名称。 Python字符串是“不可变的”,这意味着它们在创建后无法更改。
创建字符串
可以使用单引号、双引号甚至三引号来创建字符串。 Python将单引号视为双引号。
Python3
# creating string
# with single Quotes
String = 'Hello Geek'
print("Creating string with single quotes :", String)
# Creating String
# with double Quotes
String = "yes, I am Geek"
print("Creating String with double quotes :", String)
# Creating String
# with triple Quotes
String = '''yes, I am Geek'''
print("Creating String with triple quotes :", String)
Python3
# creating string
# with single quotes
String = 'Yes' I am geek'
print(String)
Python3
# this code prints the output within quotes.
# print WithQuotes within single quotes
print("'WithQuotes'")
print("Hello 'Python'")
# print WithQuotes within single quotes
print('"WithQuotes"')
print('Hello "Python"')
Python3
# creating a string
String = "GEEK"
# Show first element in string
print("The 1st element is : ", String[0])
# Show 2nd element in string
print("The 2nd element is : ", String[1])
print("The 3rd element is : ", String[2])
print("The 4th element is : ", String[3])
Python3
# creating a string
String = "GEEK"
# Show last element in string
print("The 4th element is : ", String[-1])
# Show all element in string
print("The 3rd element is : ", String[-2])
print("The 2nd element is : ", String[-3])
print("The 1th element is : ", String[-4])
Python3
# Creating string
String = "Geeks"
# assign new character
String[0] = "Hi!, Geeks"
Python3
# Creating string
String = "Hello Geeks"
print("Before updating : ", String)
# updating entire string
String = "Geeksforgeeks"
print("After updating : ", String)
# Update with indexing
String = 'Hello World!'
print("Updated String :- ", String[:6] + 'Python')
Python3
# Creating a String
String = "Geekforgeeks"
s1 = slice(3)
# print everything except the first element
print(String[s1])
# print everything UP TO the 6th index
print(String[:6])
# print everything between both index
print(String[1:7])
Python3
# Creating a String
String = "Geekforgeeks"
s1 = slice(-1)
# print everything except the last element
print(String[s1])
# print everything between both index
print(String[0:-3])
Python3
# Creating a String
String = "Geekforgeeks"
# print everything with step 1
print(String[::1])
# print everything with step 2
print(String[2::2])
# print a string backwards
print(String[::-1])
Python3
# using format option in a simple string
String = 'Geeksforgeeks'
print("{}, A computer science portal for geeks."
.format(String))
String = 'Geeks'
print("Hello {}, How are you ?".format(String))
# formatting a string using a numeric constant
val = 2
print("I want {} Burgers! ".format(val))
Python3
# Creating string
String = 'GeekForGeeks'
print(f"{String}: A Computer Science portal for geeks")
# Creating string
String = 'Geek'
print(f"Yes, I am {String}")
# Manuplating int within {}
bags = 3
book_in_bag = 12
print(f'There are total {bags * book_in_bag} books')
# work with dictionaries in f-strings
Dic = {'Portal': 'Geeksforgeeks', 'for': 'Geeks'}
print(f"{Dic['Portal']} is a computer science portal for {Dic['for']}")
Creating string with single quotes : Hello Geek
Creating String with double quotes : yes, I am Geek
Creating String with triple quotes : yes, I am Geek
注意:小心引号!
Python3
# creating string
# with single quotes
String = 'Yes' I am geek'
print(String)
输出
File "", line 3
String = 'Yes' I am geek'
^
SyntaxError: invalid syntax
上述错误的原因是Yes' I stop the 字符串中的单引号。如果你想在 python 中打印'WithQuotes' ,这不能只用单(或双)引号来完成,它需要同时使用两者。避免此错误的最佳方法是使用双引号。
例子:
Python3
# this code prints the output within quotes.
# print WithQuotes within single quotes
print("'WithQuotes'")
print("Hello 'Python'")
# print WithQuotes within single quotes
print('"WithQuotes"')
print('Hello "Python"')
'WithQuotes'
Hello 'Python'
"WithQuotes"
Hello "Python"
注意:有关详细信息,请参阅单引号和双引号 | Python
字符串索引
字符串是一个字符序列,这意味着Python可以使用索引来调用序列的一部分。有两种索引方式。
- 正索引
- 负索引
正索引
Python3
# creating a string
String = "GEEK"
# Show first element in string
print("The 1st element is : ", String[0])
# Show 2nd element in string
print("The 2nd element is : ", String[1])
print("The 3rd element is : ", String[2])
print("The 4th element is : ", String[3])
The 1st element is : G
The 2nd element is : E
The 3rd element is : E
The 4th element is : K
负索引
Python3
# creating a string
String = "GEEK"
# Show last element in string
print("The 4th element is : ", String[-1])
# Show all element in string
print("The 3rd element is : ", String[-2])
print("The 2nd element is : ", String[-3])
print("The 1th element is : ", String[-4])
The 4th element is : K
The 3rd element is : E
The 2nd element is : E
The 1th element is : G
更新字符串
在 Python 中,不允许 Python或字符字符串中的字符。这将导致错误,因为不支持从字符串中分配项目或删除项目。 Python可以允许您将新字符串重新分配给现有的字符串。
Python3
# Creating string
String = "Geeks"
# assign new character
String[0] = "Hi!, Geeks"
输出
Traceback (most recent call last):
File “/home/b298782a4e04df4950426bf4bd5bee99.py”, line 5, in
String[0] = “Hi!, Geeks”
TypeError: ‘str’ object does not support item assignment
更新整个字符串
Python3
# Creating string
String = "Hello Geeks"
print("Before updating : ", String)
# updating entire string
String = "Geeksforgeeks"
print("After updating : ", String)
# Update with indexing
String = 'Hello World!'
print("Updated String :- ", String[:6] + 'Python')
Before updating : Hello Geeks
After updating : Geeksforgeeks
Updated String :- Hello Python
字符串切片
Python切片是关于通过从头到尾分别切片来从给定字符串中获取子字符串。
Python切片可以通过两种方式完成。
- slice() 构造函数
- 扩展索引
Python3
# Creating a String
String = "Geekforgeeks"
s1 = slice(3)
# print everything except the first element
print(String[s1])
# print everything UP TO the 6th index
print(String[:6])
# print everything between both index
print(String[1:7])
Gee
Geekfo
eekfor
使用负索引切片。
Python3
# Creating a String
String = "Geekforgeeks"
s1 = slice(-1)
# print everything except the last element
print(String[s1])
# print everything between both index
print(String[0:-3])
Geekforgeek
Geekforge
我们可以使用 [ : : ] 来指定打印元素的频率。它指定从给定索引开始打印每个元素的步骤。如果没有给出任何内容,则它从第 0 个索引开始。
Python3
# Creating a String
String = "Geekforgeeks"
# print everything with step 1
print(String[::1])
# print everything with step 2
print(String[2::2])
# print a string backwards
print(String[::-1])
Geekforgeeks
efrek
skeegrofkeeG
注意:有关详细信息,请参阅Python中的字符串切片
字符串格式
str.format() 和f-strings方法用于将格式化对象添加到打印的字符串语句中。 字符串 format() 方法格式化给定的字符串。它允许多次替换和值格式化。
Python3
# using format option in a simple string
String = 'Geeksforgeeks'
print("{}, A computer science portal for geeks."
.format(String))
String = 'Geeks'
print("Hello {}, How are you ?".format(String))
# formatting a string using a numeric constant
val = 2
print("I want {} Burgers! ".format(val))
Geeksforgeeks, A computer science portal for geeks.
Hello Geeks, How are you ?
I want 2 Burgers!
注意:有关更多信息,请参阅Python |格式()函数
格式化的 f 字符串字面量以 'f' 和花括号 { } 为前缀,其中包含将替换为其值的表达式。
Python3
# Creating string
String = 'GeekForGeeks'
print(f"{String}: A Computer Science portal for geeks")
# Creating string
String = 'Geek'
print(f"Yes, I am {String}")
# Manuplating int within {}
bags = 3
book_in_bag = 12
print(f'There are total {bags * book_in_bag} books')
# work with dictionaries in f-strings
Dic = {'Portal': 'Geeksforgeeks', 'for': 'Geeks'}
print(f"{Dic['Portal']} is a computer science portal for {Dic['for']}")
GeekForGeeks: A Computer Science portal for geeks
Yes, I am Geek
There are total 36 books
Geeksforgeeks is a computer science portal for Geeks
注意:有关更多信息,请参阅Python 3 中的 f-strings – 格式化字符串字面量