点符号字符串操作 [英] Dot notation string manipulation
问题描述
有没有办法使用以下方式在 Python 中操作字符串?
Is there a way to manipulate a string in Python using the following ways?
对于任何以点表示法存储的字符串,例如:
For any string that is stored in dot notation, for example:
s = "classes.students.grades"
有没有办法将字符串更改为以下内容:
Is there a way to change the string to the following:
"classes.students"
基本上,删除包括上一期在内的所有内容.所以 "restaurants.spanish.food.salty"
会变成 "restaurants.spanish.food"
.
Basically, remove everything up to and including the last period. So "restaurants.spanish.food.salty"
would become "restaurants.spanish.food"
.
另外,有什么方法可以确定最后一个时期之后发生了什么?我想这样做的原因是我想使用 isDigit()
.
Additionally, is there any way to identify what comes after the last period? The reason I want to do this is I want to use isDigit()
.
所以,如果是 classes.students.grades.0
我可以以某种方式获取 0
,所以我可以使用带有 isdigit的 if 语句code>,然后说如果最后一个句点之后的字符串部分(在这种情况下为
0
)是一个数字,则将其删除,否则,保留它.
So, if it was classes.students.grades.0
could I grab the 0
somehow, so I could use an if statement with isdigit
, and say if the part of the string after the last period (so 0
in this case) is a digit, remove it, otherwise, leave it.
推荐答案
s = "classes.students.grades"
print '.'.join(s.split('.')[:-1])
您在 上拆分字符串.
- 它会给您一个字符串列表,之后您将列表元素连接回用 分隔它们的字符串.
You are splitting the string on .
- it'll give you a list of strings, after that you are joining the list elements back to string separating them by .
[:-1]
将选择列表中的所有元素,但最后一个
[:-1]
will pick all the elements from the list but the last one
检查最后一个之后的内容.
:
s.split('.')[-1]
另一种方法是使用 rsplit
.它的工作方式与 split 相同,但如果您提供 maxsplit 参数,它将从末尾开始拆分字符串:
Another way is to use rsplit
. It works the same way as split but if you provide maxsplit parameter it'll split the string starting from the end:
rest, last = s.rsplit('.', 1)
'classes.students'
'grades'
您也可以使用re.sub
用空字符串替换最后一个 .
之后的部分:
You can also use re.sub
to substitute the part after the last .
with an empty string:
re.sub('\.[^.]+$', '', s)
你的问题的最后一部分是用 []
换行,我建议使用 format
和 列表理解
:
And the last part of your question to wrap words in []
i would recommend to use format
and list comprehension
:
''.join("[{}]".format(e) for e in s.split('.'))
它会给你想要的输出:
[classes][students][grades]
这篇关于点符号字符串操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!