Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

python - Dot notation string manipulation

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"

Basically, remove everything up to and including the last period. So "restaurants.spanish.food.salty" would become "restaurants.spanish.food".

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().

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use split and join together:

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] will pick all the elements from the list but the last one

To check what comes after the last .:

s.split('.')[-1]

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'

You can also use re.sub to substitute the part after the last . with an empty string:

re.sub('.[^.]+$', '', s)

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('.'))

It'll give you the desired output:

[classes][students][grades]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...