python - 如何只保留一列中第一个空白字符之前的子字符串?
问题描述
这是我的数据样本:
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。
我该如何解决这个问题?
解决方案
让我们使用示例字符串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)
推荐阅读
- moodle - 创建一个直接链接到 SCORM 包的 Moodle 课程
- android - 无法通过 RecyclerView 显示来自 Firebase 数据库的所有消息
- c# - 在 .Net Core 项目中使用 .Net Framework dll (v4.7.2)
- c++ - 将不均匀的文件读入结构
- c# - 根据消费者选择在 Blazor 组件中发出不同的标签
- go - 字段上未定义的验证函数“xxx”
- python - MySQL 和 Python,搜索数据库
- sql - 如何选择 cte 一次更新多个表列?
- analytics - 网站究竟如何连接到 adobe 分析?
- python - 对象内的条件过滤 Django