首页 > 解决方案 > 如何只保留一列中第一个空白字符之前的子字符串?

问题描述

这是我的数据样本:

a=pd.DataFrame({'ID':[1,2,3,4,5],
                'Str':['aa aafae afre ht4','v fef 433','1234334 a','bijf 049tu0q4g vie','aaa 1']})

现在我只想在第一个空白字符之前保留子字符串。我可以找到第一个空白字符的位置。但我不知道下一部分该怎么做。

我正在尝试打印一个句子的前三个单词的第一个字母,但在d4 = y.find(" ", d3)部分中,程序不会将其识别为整数,如果我将其转换为整数,则会导致错误,因为我'以 10 为底的 m。

我该如何解决这个问题?

标签: pythonstringpandasfindsubstring

解决方案


让我们使用示例字符串this is just a test

如果空格只是空格

你可以这样做:

test = "this is just a test"
first_word = test.split(" ")[0]
print(first_word)

这将导致this

我在这里做的是

  • 按空格将字符串拆分为单词数组:test.split(" ")
  • 仅选择位置 0 的第一个元素:[0]

如果空格可以是任何空格(空格、制表符等)

您可以像这样使用正则表达式:

import re

test = "this is just a test"
first_word = re.sub('\s.*', '', test)
print(first_word)

在这里,我搜索第一次出现的空格 ('\s'),后跟任何文本 ( .*),然后将其替换为空 ( '')。

如果你想使用查找

test = "this is just a test"
space_pos = test.find(" ")
first_word = test[:space_pos]
print(first_word)

推荐阅读