python 分割字串_在Python中分割,连结和连结字串

python 分割字串

There are few guarantees in life: death, taxes, and programmers needing to deal with strings. Strings can come in many forms. They could be unstructured text, usernames, product descriptions, database column names, or really anything else that we describe using language.

生活中几乎没有保证:死亡,税收和程序员需要处理字符串。 字符串可以有多种形式。 它们可以是非结构化的文本,用户名,产品说明,数据库列名称,或者实际上是我们使用语言描述的其他任何内容。

With the near-ubiquity of string data, it’s important to master the tools of the trade when it comes to strings. Luckily, Python makes string manipulation very simple, especially when compared to other languages and even older versions of Python.

在字符串数据几乎无处不在的情况下,掌握有关字符串的交易工具非常重要。 幸运的是,Python使字符串操作非常简单,特别是与其他语言甚至旧版本的Python相比时。

In this article, you will learn some of the most fundamental string operations: splitting, concatenating, and joining. Not only will you learn how to use these tools, but you will walk away with a deeper understanding of how they work under the hood.

在本文中,您将学习一些最基本的字符串操作:拆分,连接和联接。 您不仅将学习如何使用这些工具,而且还将对它们在幕后的工作方式有更深入的了解。

Take the Quiz: Test your knowledge with our interactive “Splitting, Concatenating, and Joining Strings in Python” quiz. Upon completion you will receive a score so you can track your learning progress over time.

参加测验:通过我们的交互式“在Python中拆分,连接和连接字符串”测验,测试您的知识。 完成后,您将获得一个分数,以便您可以随时间追踪学习进度。

Click here to start the quiz »

点击此处开始测验»

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

免费奖金: 单击此处获取Python备忘单,并学习Python 3的基础知识,例如使用数据类型,字典,列表和Python函数。

分割字符串 (Splitting Strings)

In Python, strings are represented as str objects, which are immutable: this means that the object as represented in memory can not be directly altered. These two facts can help you learn (and then remember) how to use .split().

在Python中,字符串表示为不可更改的str对象:这意味着不能直接更改内存中表示的对象。 这两个事实可以帮助您学习(然后记住)如何使用.split()

Have you guessed how those two features of strings relate to splitting functionality in Python? If you guessed that .split() is an instance method because strings are a special type, you would be correct! In some other languages (like Perl), the original string serves as an input to a standalone .split() function rather than a method called on the string itself.

您是否猜想过这两个字符串功能与Python中的拆分功能有何关系? 如果您因为字符串是一种特殊类型而猜测.split()是一个实例方法 ,那将是正确的! 在某些其他语言(如Perl)中,原始字符串用作独立.split()函数的输入,而不是在字符串本身上调用的方法。

Note: Ways to Call String Methods

注意:调用字符串方法的方法

String methods like .split() are mainly shown here as instance methods that are called on strings. They can also be called as static methods, but this isn’t ideal because it’s more “wordy.” For the sake of completeness, here’s an example:

.split()这样的字符串方法在这里主要显示为在字符串上调用的实例方法。 也可以将它们称为静态方法,但这并不理想,因为它更“罗word”。 为了完整起见,下面是一个示例:

 # Avoid this:
# Avoid this:
strstr .. splitsplit (( 'a,b,c''a,b,c' , , ','',' )
)

This is bulky and unwieldy when you compare it to the preferred usage:

将其与首选用法进行比较时,它笨重且笨拙:

For more on instance, class, and static methods in Python, check out our in-depth tutorial.

有关Python中的实例,类和静态方法的更多信息,请查看我们的深入教程

What about string immutability? This should remind you that string methods are not in-place operations, but they return a new object in memory.

字符串不可变怎么办? 这应该提醒您,字符串方法不是就地操作 ,但它们会在内存中返回一个新对象。

Note: In-Place Operations

注意:就地操作

In-place operations are operations that directly change the object on which they are called. A common example is the .append() method that is used on lists: when you call .append() on a list, that list is directly changed by adding the input to .append() to the same list.

就地操作是直接更改调用它们的对象的操作。 一个常见的示例是在列表上使用的.append()方法:当您在列表上调用.append()时,通过将.append()的输入添加到同一列表来直接更改该列表。

不带参数分割 (Splitting Without Parameters)

Before going deeper, let’s look at a simple example:

在深入探讨之前,让我们看一个简单的示例:

>>>
>>> 'this is my string'.split()
['this', 'is', 'my', 'string']

>>>

This is actually a special case of a .split() call, which I chose for its simplicity. Without any separator specified, .split() will count any whitespace as a separator.

实际上,这是.split()调用的特例,我为简单起见选择了它。 如果未指定任何分隔符, .split()会将任何空格都计为分隔符。

Another feature of the bare call to .split() is that it automatically cuts out leading and trailing whitespace, as well as consecutive whitespace. Compare calling .split() on the following string without a separator parameter and with having ' ' as the separator parameter:

.split()的裸调用的另一个功能是,它会自动剪切掉前导和尾随的空格以及连续的空格。 比较在以下字符串上调用.split()时没有分隔符参数,并且以' '作为分隔符参数的情况:

>>>
>>> s = ' this   is  my string '
>>> s.split()
['this', 'is', 'my', 'string']
>>> s.split(' ')
['', 'this', '', '', 'is', '', 'my', 'string', '']

>>>

The first thing to notice is that this showcases the immutability of strings in Python: subsequent calls to .split() work on the original string, not on the list result of the first call to .split().

首先要注意的是,这展示了Python中字符串的不变性:对.split()后续调用在原始字符串上起作用,而不是在首次调用.split()的列表结果上起作用。

The second—and the main—thing you should see is that the bare .split() call extracts the words in the sentence and discards any whitespace.

第二个也是最主要的事情是,裸露的.split()调用会提取句子中的单词,并丢弃所有空格。

指定分隔符 (Specifying Separators)

.split(' '), on the other hand, is much more literal. When there are leading or trailing separators, you’ll get an empty string, which you can see in the first and last elements of the resulting list.

另一方面, .split(' ')更为文字。 当有前导或尾随分隔符时,您将获得一个空字符串,您可以在结果列表的第一个和最后一个元素中看到该字符串。

Where there are multiple consecutive separators (such as between “this” and “is” and between “is” and “my”), the first one will be used as the separator, and the subsequent ones will find their way into your result list as empty strings.

如果有多个连续的分隔符(例如“ this”和“ is”之间以及“ is”和“ my”之间),则第一个将用作分隔符,随后的分隔符将进入结果列表作为空字符串。

Note: Separators in Calls to .split()

注意:调用.split()分隔符

While the above example uses a single space character as a separator input to .split(), you aren’t limited in the types of characters or length of strings you use as separators. The only requirement is that your separator be a string. You could use anything from "..." to even "separator".

尽管上面的示例使用单个空格字符作为.split()的分隔符输入,但您不受限于用作分隔符的字符类型或字符串长度。 唯一的要求是您的分隔符必须是字符串。 您可以使用从"..."甚至是"separator"

用Maxsplit限制拆分 (Limiting Splits With Maxsplit)

.split() has another optional parameter called maxsplit. By default, .split() will make all possible splits when called. When you give a value to maxsplit, however, only the given number of splits will be made. Using our previous example string, we can see maxsplit in action:

.split()具有另一个可选参数,称为maxsplit 。 默认情况下, .split()将在调用时进行所有可能的分割。 但是,当给maxsplit值时,只会进行给定的分割数。 使用前面的示例字符串,我们可以看到maxsplit的作用:

>>>
>>> s = "this is my string"
>>> s.split(maxsplit=1)
['this', 'is my string']

>>>

As you see above, if you set maxsplit to 1, the first whitespace region is used as the separator, and the rest are ignored. Let’s do some exercises to test out everything we’ve learned so far.

如上所示,如果将maxsplit设置为1 ,则第一个空格区域将用作分隔符,其余的将被忽略。 让我们做一些练习来测试到目前为止我们学到的一切。

What happens when you give a negative number as the maxsplit parameter?

当您给负数作为maxsplit参数时会发生什么?

.split() will split your string on all available separators, which is also the default behavior when maxsplit isn’t set.

.split()将在所有可用的分隔符上分割字符串,这也是未设置maxsplit时的默认行为。

You were recently handed a comma-separated value (CSV) file that was horribly formatted. Your job is to extract each row into an list, with each element of that list representing the columns of that file. What makes it badly formatted? The “address” field includes multiple commas but needs to be represented in the list as a single element!

您最近收到了一个逗号分隔值(CSV)文件,该文件的格式很糟糕。 您的工作是将每一行提取到一个列表中,该列表的每个元素代表该文件的列。 是什么导致其格式错误? “地址”字段包含多个逗号,但需要在列表中表示为单个元素!

Assume that your file has been loaded into memory as the following multiline string:

假设您的文件已作为以下多行字符串加载到内存中:

Name,Phone,Address
Mike Smith,15554218841,123 Nice St, Roy, NM, USA
Anita Hernandez,15557789941,425 Sunny St, New York, NY, USA
Guido van Rossum,315558730,Science Park 123, 1098 XG Amsterdam, NL
Name,Phone,Address
Mike Smith,15554218841,123 Nice St, Roy, NM, USA
Anita Hernandez,15557789941,425 Sunny St, New York, NY, USA
Guido van Rossum,315558730,Science Park 123, 1098 XG Amsterdam, NL

Your output should be a list of lists:

您的输出应为列表列表:

Each inner list represents the rows of the CSV that we’re interested in, while the outer list holds it all together.

每个内部列表代表我们感兴趣的CSV行,而外部列表将所有内容都保存在一起。

Here’s my solution. There are a few ways to attack this. The important thing is that you used .split() with all its optional parameters and got the expected output:

这是我的解决方案。 有几种方法可以解决此问题。 重要的是,您将.split()及其所有可选参数一起使用,并获得了预期的输出:

 input_string input_string = = """Name,Phone,Address
"""Name,Phone,Address
Mike Smith,15554218841,123 Nice St, Roy, NM, USA
Mike Smith,15554218841,123 Nice St, Roy, NM, USA
Anita Hernandez,15557789941,425 Sunny St, New York, NY, USA
Anita Hernandez,15557789941,425 Sunny St, New York, NY, USA
Guido van Rossum,315558730,Science Park 123, 1098 XG Amsterdam, NL"""

Guido van Rossum,315558730,Science Park 123, 1098 XG Amsterdam, NL"""

def def string_split_exstring_split_ex (( unsplitunsplit ):
    ):
    results results = = []

    []

    # Bonus points for using splitlines() here instead, 
    # Bonus points for using splitlines() here instead, 
    # which will be more readable
    # which will be more readable
    for for line line in in unsplitunsplit .. splitsplit (( '' nn '' )[)[ 11 :]:
        :]:
        resultsresults .. appendappend (( lineline .. splitsplit (( ','',' , , maxsplitmaxsplit == 22 ))

    ))

    return return results

results

printprint (( string_split_exstring_split_ex (( inputinput ))
))

We call .split() twice here. The first usage can look intimidating, but don’t worry! We’ll step through it, and you’ll get comfortable with expressions like these. Let’s take another look at the first .split() call: unsplit.split('n')[1:].

我们在这里两次调用.split() 。 第一次使用可能看起来令人生畏,但请放心! 我们将逐步解决,您将对这些表达式感到满意。 让我们再看一下第一个.split()调用: unsplit.split('n')[1:]

The first element is unsplit, which is just the variable that points to your input string. Then we have our .split() call: .split('n'). Here, we are splitting on a special character called the newline character.

第一个元素是unsplit ,它只是指向您输入字符串的变量。 然后,我们调用.split() .split('n') 。 在这里,我们拆分为一个称为换行符的特殊字符

What does n do? As the name implies, it tells whatever is reading the string that every character after it should be shown on the next line. In a multiline string like our input_string, there is a hidden n at the end of each line.

n该怎么办? 顾名思义,它告诉正在读取字符串的每个字符之后的每个字符都应显示在下一行。 在像我们的input_string这样的多行字符串中,每行末尾都有一个隐藏的n

The final part might be new: [1:]. The statement so far gives us a new list in memory, and [1:] looks like a list index notation, and it is—kind of! This extended index notation gives us a list slice. In this case, we take the element at index 1 and everything after it, discarding the element at index 0.

最后一部分可能是新的: [1:] 。 到目前为止,该语句为我们提供了一个内存中的新列表, [1:]看起来像一个列表索引符号,它是–有点! 这种扩展的索引表示法为我们提供了列表切片 。 在这种情况下,我们采用索引1处的元素及其后的所有内容,并丢弃索引0处的元素。

In all, we iterate through a list of strings, where each element represents each line in the multiline input string except for the very first line.

总而言之,我们遍历字符串列表,其中每个元素代表多行输入字符串中除第一行之外的每一行。

At each string, we call .split() again using , as the split character, but this time we are using maxsplit to only split on the first two commas, leaving the address intact. We then append the result of that call to the aptly named results array and return it to the caller.

在每一个串,我们称之为.split()再次使用,作为分割字符,但这次我们使用maxsplit只拆分前两个逗号,留下地址不变。 然后,我们将该调用的结果附加到适当命名的results数组中,并将其返回给调用方。

串联和连接字符串 (Concatenating and Joining Strings)

The other fundamental string operation is the opposite of splitting strings: string concatenation. If you haven’t seen this word, don’t worry. It’s just a fancy way of saying “gluing together.”

字符串的另一种基本操作与拆分字符串相反:字符串连接 。 如果您还没有看到这个词,请不要担心。 这只是说“粘合在一起”的一种奇特的方式。

+运算符串联 (Concatenating With the + Operator)

There are a few ways of doing this, depending on what you’re trying to achieve. The simplest and most common method is to use the plus symbol (+) to add multiple strings together. Simply place a + between as many strings as you want to join together:

有几种方法可以做到这一点,具体取决于您要实现的目标。 最简单,最常见的方法是使用加号( + )将多个字符串加在一起。 只需在要连接的任意多个字符串之间放置一个+

>>>
>>>
 >>>  'a' + 'b' + 'c'
'abc'

In keeping with the math theme, you can also multiply a string to repeat it:

与数学主题保持一致,您还可以将字符串相乘以重复该主题:

>>>
>>>
 >>>  'do' * 2
'dodo'

Remember, strings are immutable! If you concatenate or repeat a string stored in a variable, you will have to assign the new string to another variable in order to keep it.

记住,字符串是不可变的! 如果连接或重复存储在变量中的字符串,则必须将新字符串分配给另一个变量以保留它。

>>>
>>>
 >>>  orig_string = 'Hello'
>>>  orig_string + ', world'
'Hello, world'
>>>  orig_string
'Hello'
>>>  full_sentence = orig_string + ', world'
>>>  full_sentence
'Hello, world'

If we didn’t have immutable strings, full_sentence would instead output 'Hello, world, world'.

如果我们没有不变的字符串, full_sentence会输出'Hello, world, world'

Another note is that Python does not do implicit string conversion. If you try to concatenate a string with a non-string type, Python will raise a TypeError:

另一个注意事项是Python不执行隐式字符串转换。 如果您尝试将非字符串类型的字符串连接起来,Python将引发TypeError

>>>
>>>
 >>>  'Hello' + 2
Traceback (most recent call last):
  File "<stdin>" , line 1 , in <module>
TypeError : must be str, not int

This is because you can only concatenate strings with other strings, which may be new behavior for you if you’re coming from a language like JavaScript, which attempts to do implicit type conversion.

这是因为您只能将字符串与其他字符串连接在一起,如果您来自尝试进行隐式类型转换JavaScript之类的语言,那么这对于您来说可能是新的行为。

.Join()串联 (Concatenating With .Join())

There is another, more powerful, way to join strings together: the join() method.

还有另一种将字符串连接在一起的更强大的方法: join()方法。

The common use case here is when you have an iterable—like a list—made up of strings, and you want to combine those strings into a single string. Like .split(), .join() is a string instance method. If all of your strings are in an iterable, which one do you call .join() on?

这里的常见用例是当您有一个由字符串组成的可迭代对象(如列表),并且想要将这些字符串组合成一个字符串时。 与.split().join()是一个字符串实例方法。 如果您所有的字符串都处于可迭代状态,则对.join()调用哪一个?

This is a bit of a trick question. Remember that when you use .split(), you call it on the string or character you want to split on. The opposite operation is .join(), so you call it on the string or character you want to use to join your iterable of strings together:

这是一个技巧问题。 请记住,当您使用.split() ,会在您想分割的字符串或字符上调用它。 相反的操作是.join() ,因此您在要用于将可迭代的字符串连接在一起的字符串或字符上调用它:

>>>
>>>
 >>>  strings = [ 'do' , 're' , 'mi' ]
>>>  ',' . join ( strings )
'do,re,mi'

Here, we join each element of the strings list with a comma (,) and call .join() on it rather than the strings list.

在这里,我们使用逗号( , )将strings列表的每个元素连接在一起,并在其上调用.join()而不是strings列表。

How could you make the output text more readable?

您如何使输出文本更具可读性?

One thing you could do is add spacing:

您可以做的一件事是增加间距:

>>>
>>>
 >>>  strings = [ 'do' , 're' , 'mi' ]
>>>  ', ' . join ( strings )
'do, re, mi'

By doing nothing more than adding a space to our join string, we’ve vastly improved the readability of our output. This is something you should always keep in mind when joining strings for human readability.

除了在连接字符串中添加空格外,我们已经极大地提高了输出的可读性。 连接字符串以提高可读性时,应始终牢记这一点。

.join() is smart in that it inserts your “joiner” in between the strings in the iterable you want to join, rather than just adding your joiner at the end of every string in the iterable. This means that if you pass an iterable of size 1, you won’t see your joiner:

.join()很聪明,因为它将“ joiner”插入到要联接的可迭代对象的字符串之间,而不是仅将joiner添加到可迭代对象的每个字符串的末尾。 这意味着,如果传递的大小为1 ,则您将看不到您的连接器:

>>>
>>>
 >>>  'b' . join ([ 'a' ])
'a'

Using our web scraping tutorial, you’ve built a great weather scraper. However, it loads string information in a list of lists, each holding a unique row of information you want to write out to a CSV file:

使用我们的网络抓取教程 ,您已经构建了出色的天气抓取工具 。 但是,它将字符串信息加载到列表列表中,每个列表都包含您要写到CSV文件的唯一信息行:

Your output should be a single string that looks like this:

您的输出应为单个字符串,如下所示:

 """
"""
Boston,MA,76F,65% Precip,0.15in
Boston,MA,76F,65% Precip,0.15in
San Francisco,CA,62F,20% Precip,0.00 in
San Francisco,CA,62F,20% Precip,0.00 in
Washington,DC,82F,80% Precip,0.19 in
Washington,DC,82F,80% Precip,0.19 in
Miami,FL,79F,50% Precip,0.70 in
Miami,FL,79F,50% Precip,0.70 in
"""
"""

For this solution, I used a list comprehension, which is a powerful feature of Python that allows you to rapidly build lists. If you want to learn more about them, check out this great article that covers all the comprehensions available in Python.

对于此解决方案,我使用了列表理解功能,这是Python的强大功能,可让您快速构建列表。 如果您想了解有关它们的更多信息,请查看这篇涵盖Python中所有可用理解的出色文章

Below is my solution, starting with a list of lists and ending with a single string:

以下是我的解决方案,以列表列表开头,以单个字符串结尾:

Here we use .join() not once, but twice. First, we use it in the list comprehension, which does the work of combining all the strings in each inner list into a single string. Next, we join each of these strings with the newline character n that we saw earlier. Finally, we simply print the result so we can verify that it is as we expected.

在这里,我们不使用.join()一次,而是两次。 首先,我们在列表理解中使用它,该工作将每个内部列表中的所有字符串组合为一个字符串。 接下来,我们将每个字符串与前面看到的换行符n 。 最后,我们仅打印结果,以便可以验证它是否符合我们的预期。

绑在一起 (Tying It All Together)

While this concludes this overview of the most basic string operations in Python (splitting, concatenating, and joining), there is still a whole universe of string methods that can make your experiences with manipulating strings much easier.

虽然本文概述了Python中最基本的字符串操作(拆分,连接和联接),但仍然有大量的字符串方法可以使您处理字符串的经验更加轻松。

Once you have mastered these basic string operations, you may want to learn more. Luckily, we have a number of great tutorials to help you complete your mastery of Python’s features that enable smart string manipulation:

掌握了这些基本的字符串操作后,您可能需要了解更多信息。 幸运的是,我们有许多很棒的教程可以帮助您完成对Python功能的精通,这些功能可实现智能字符串操作:

Take the Quiz: Test your knowledge with our interactive “Splitting, Concatenating, and Joining Strings in Python” quiz. Upon completion you will receive a score so you can track your learning progress over time.

参加测验:通过我们的交互式“在Python中拆分,连接和连接字符串”测验,测试您的知识。 完成后,您将获得一个分数,以便您可以随时间追踪学习进度。

Click here to start the quiz »

点击此处开始测验»

翻译自: https://www.pybloggers.com/2018/10/splitting-concatenating-and-joining-strings-in-python/

python 分割字串