学习python?下面是如何操作字符串

在Python中使用和操作字符串可能看起来很困难,但这是一个很简单的欺骗。...

使用Python可以通过多种方式操纵字符串。Python提供了各种函数、操作符和方法,可以用来操作字符串。您可以分割一个字符串,连接两个或多个字符串,在字符串中**变量,等等。

django-of-flask-which-python-web-framework-should-you-learn-featured

Python中的字符串可以定义为一系列字符。它们是不可变的,这意味着一旦声明它们就不能修改。相反,为操作目的创建字符串副本。

如何在python中创建字符串

在Python中创建字符串就像在Python中为变量赋值一样简单。可以使用单引号(“”)、双引号(“”)或三个单引号(“”)/双引号(“”)来创建字符串。

str1 = 'Hello!'
str2 = "Hello!"
str3 = """Hello!"""
str4 = '''Hello!'''
print(str1)
print(str2)
print(str3)
print(str4)

输出:

Hello!
Hello!
Hello!
Hello!

使用双引号创建字符串的优点是,可以在双引号内使用单引号字符。Python将单引号字符视为字符串的一部分。

s = "Using 'single quote' inside double quotes"
print(s)

输出:

Using 'single quote' inside double quotes

如果要创建多行字符串,那么使用三个单引号(“”)/三个双引号(“”)是最佳选择。在使用单引号(“”)或双引号(“”)创建字符串时,需要对新行使用转义符(换行符)。但如果用三个引号,你就不需要这么做了。

s1 = """This is a multiline
string using three double quotes"""
s2 = "This is a multiline
string using double quotes"
print(s1)
print(s2)

输出:

This is a multiline
string using three double quotes
This is a multiline
string using double quotes

如何访问字符串

如果要访问单个字符,则使用索引;如果要访问一系列字符,则使用切片。

Slicing and Indexing in Python Strings

字符串索引

与任何其他Python数据类型一样,字符串索引从0开始。索引的范围从0到字符串的长度-1。Python字符串还支持负索引:-1指向字符串的最后一个字符,-2指向字符串的最后第二个字符,依此类推。

s = "MAKEUSEOF"
# Prints whole string
print(s)
# Prints 1st character
print(s[0])
# Prints 2nd character
print(s[1])
# Prints last character
print(s[-1])
# Prints 2nd last character
print(s[-2])

输出:

MAKEUSEOF
M
A
F
O

您必须使用整数访问字符否则,您将得到一个TypeError。如果您试图访问超出范围的元素,也会发生这种情况。

类型错误:

s = "MAKEUSEOF"
# TypeError will be thrown if you don't use integers
print(s[1.5])

输出:

TypeError: string indices must be integers

索引器:

s = "MAKEUSEOF"
# IndexError will be thrown if you try to use index out of range
print(s[88])

输出:

TypeError: string indices must be integers

线切割

可以使用冒号运算符(:)访问一系列字符。

s = "MAKEUSEOF"
# Prints from 0th index(included) to 4th index(excluded)
print(s[0:4])
# Prints from 3rd last index(included) to last index(excluded)
print(s[-3:-1])
# Prints from 2nd index to last of the string
print(s[2:])
# Prints from start of the string to 6th index(excluded)
print(s[:6])

输出:

MAKE
EO
KEUSEOF
MAKEUS

如何在字符串上使用运算符

使用+运算符

+运算符用于连接两个或多个字符串。它返回结果串联字符串。

s1 = "MAKE"
s2 = "USE"
s3 = "OF"
s = s1 + s2 + s3
# Prints the concatenated string
print(s)

输出:

MAKEUSEOF

使用*运算符

用于将字符串重复给定次数。

str = "MUO-"
# Prints str 5 times
print(str * 5)
# Prints str 2 times
print(2 * str)
x = 3
# Prints str x times
# Here, x = 3
print(str * x)

输出:

MUO-MUO-MUO-MUO-MUO-
MUO-MUO-
MUO-MUO-MUO-

使用in运算符

这是一个成员运算符,用于检查第一个操作数是否存在于第二个操作数中。如果第一个操作数出现在第二个操作数中,则返回True。

否则返回False。

str = "MAKEUSEOF"
# Returns True as MAKE is present in str
print("MAKE" in str)
# Returns False as H is not present in str
print("H" in str)

输出:

True
False

使用not in运算符

另一个成员操作符,not in与in操作符相反。如果第一个操作数出现在第二个操作数中,则返回False。否则返回True。

str = "MAKEUSEOF"
# Returns True as Hello is not present in str
print("Hello" not in str)
# Returns False as M is present in str
print("M" not in str)

输出:

True
False

字符串中的转义序列

使用转义序列可以在字符串中放置特殊字符。您只需在要转义的字符之前添加一个反斜杠(/)。如果不转义字符,Python将抛出一个错误。

s = 'We are using apostrophe \' in our string'
print(s)

输出:

We are using apostrophe ' in our string

如何在字符串中**变量

通过在花括号中**变量,可以在字符串内部使用变量。此外,在打开字符串的引号之前,还需要添加小写f或大写f。

s1 = "Piper"
s2 = "a"
s3 = "pickled"
str = f"Peter {s1} picked {s2} peck of {s3} peppers"
# s1, s2 and s3 are replaced by their values
print(str)
a = 1
b = 2
c = a + b
# a, b and c are replaced by their values
print(f"Sum of {a} + {b} is equal to {c}")

输出:

Peter Piper picked a peck of pickled peppers
Sum of 1 + 2 is equal to 3

如何使用内置字符串函数

len()函数

此函数用于查找字符串的长度。它是Python中最常用的函数之一。

str = "MAKEUSEOF"
# Prints the number of characters in "MAKEUSEOF"
print(len(str))

输出:

9

ord()函数

同时该函数用于查找字符的整数值。Python是一种通用语言,它支持ASCII和Unicode字符。

c1 = ord('M')
c2 = ord('a')
c3 = ord('A')
c4 = ord('$')
c5 = ord('#')
print(c1)
print(c2)
print(c3)
print(c4)
print(c5)

输出:

77
97
65
36
35

chr()函数

使用chr()查找整数的字符值。

i1 = chr(77)
i2 = chr(97)
i3 = chr(65)
i4 = chr(36)
i5 = chr(35)
print(i1)
print(i2)
print(i3)
print(i4)
print(i5)

输出:

M
a
A
$
#

相关:什么是ASCII文本,它是如何使用的?

str()函数

使用此函数可以将任何Python对象转换为字符串。

num = 73646
# Converts num (which is integer) to string
s = str(num)
# Prints the string
print(s)
# Type functi*** returns the type of object
# Here, <class 'str'> is returned
print(type(s))

输出:

73646
<class 'str'>

如何在python中连接和拆分字符串

拆分字符串

可以使用split()方法将字符串拆分为基于分隔符的字符串列表。

str1 = "Peter-Piper-picked-a-peck-of-pickled-peppers"
splitted_list1 = str1.split('-')
# Prints the list of strings that are split by - delimiter
print(splitted_list1)
str2 = "We surely shall see the sun shine soon"
splitted_list2 = str2.split(' ')
# Prints the list of strings that are split by a single space
print(splitted_list2)

输出:

['Peter', 'Piper', 'picked', 'a', 'peck', 'of', 'pickled', 'peppers']
['We', 'surely', 'shall', 'see', 'the', 'sun', 'shine', 'soon']

连接字符串

可以使用join()方法连接iterable对象的所有元素。可以使用要加入元素的任何分隔符。

list1 = ["I", "thought", "I", "thought", "of", "thinking", "of", "thanking", "you"]
# Joins the list as a string by using - as a delimiter
str1 = "-".join(list1)
print(str1)
list2 = ["Ed", "had", "edited", "it"]
# Joins the list as a string by using a single space as a delimiter
str2 = " ".join(list2)
print(str2)

输出:

I-thought-I-thought-of-thinking-of-thanking-you
Ed had edited it

现在你明白了字符串操作

处理字符串和文本是编程不可或缺的一部分。字符串充当从程序向程序用户传递信息的媒介。使用Python可以按照您想要的方式操纵字符串。

  • 发表于 2021-03-11 10:21
  • 阅读 ( 327 )
  • 分类:编程

你可能感兴趣的文章

水蟒(anaconda)和python编程(python programming)的区别

...费的,开源的,跨平台的。它还支持数据类型,如数值、字符串、列表、元组和字典。Python是一种多范式编程语言,支持过程式编程和面向对象编程。此外,它是一种基于解释器的语言。解释器逐行读取源代码。因此,它是一种...

  • 发布于 2020-10-18 11:25
  • 阅读 ( 322 )

菲律宾比索(php)和python(python)的区别

...HTML代码。PHP中有各种数据类型,如整数、布尔值、Null、字符串、数组和对象。PHP可用于文件操作,如打开、关闭、读取和写入文件。可以处理数据收集和发送电子邮件的表格。PHP支持HTTP cookies。Cookie用于跟踪目的。这些是存储...

  • 发布于 2020-10-18 23:19
  • 阅读 ( 265 )

蟒蛇2(python 2)和三(3)的区别

...浮点数的答案。7/2等于3.5。 Unicode支持 要使python2中的字符串为Unicode,应使用字符“u”。e、 g.u“你好” 在Python3中,字符串默认为Unicode。 Raw_Input()函数 在Python2中,raw_input()函数用于从用户获取输入。此函数用于读...

  • 发布于 2020-10-20 01:55
  • 阅读 ( 345 )

学习python?下面是如何复制文件

...果您是Python的新手,那么您可能仍然需要采用某种方法来学习。因此,让我们通过本文了解如何使用Python复制文件。 ...

  • 发布于 2021-03-11 10:45
  • 阅读 ( 336 )

如何在python中使用列表理解

... 用Python创建项目列表很容易。但是,当您需要从数学或字符串操作生成值或项的列表时,该任务可能会变得有点乏味。这时使用列表理解就派上用场了。 ...

  • 发布于 2021-03-11 10:55
  • 阅读 ( 576 )

json-python解析:简单指南

... 当您有一个包含JSON数据的字符串时,可以使用以下命令将其转换为python对象(或列表): ...

  • 发布于 2021-03-13 11:20
  • 阅读 ( 281 )

9个最好的pi编程资源,把你的树莓pi使用

...programming on the Pi涵盖Python语言的基础知识、列表、字典和字符串,以及类和模块。有一个关于游戏编程和硬件接口的部分。编程Raspberry Pi:Getting Started with Python是使用Python进行Pi编程的最佳书籍。 ...

  • 发布于 2021-03-14 03:57
  • 阅读 ( 233 )

用这些免费的在线交互式shell在浏览器中试用python

如果您正在考虑学习Python,那么您可能会被初始设置过程弄得不知所措。您需要在系统上安装Python,然后学习如何使用命令行处理代码,或者学习如何使用交互式shell,或者学习如何设置pythonide。 ...

  • 发布于 2021-03-15 00:25
  • 阅读 ( 369 )

数组和列表在python中的工作方式

...数组的主要警告是,所有数据必须相同——不能存储混合字符串和整数。几乎总是需要指定要存储多少元素。可变大小或动态数组确实存在,但固定长度数组更容易开始。 ...

  • 发布于 2021-03-15 17:19
  • 阅读 ( 229 )

如何让python和javascript使用json进行通信

...何合适的名称。这个方法里面是一个简单的你好,世界!字符串。最后,将脚本设置为在请求时实际运行: ...

  • 发布于 2021-03-16 01:22
  • 阅读 ( 293 )