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
567 views
in Technique[技术] by (71.8m points)

python - Slicing strings in str.format

I want to achieve the following with str.format:

x,y = 1234,5678
print str(x)[2:] + str(y)[:2]

The only way I was able to do it was:

print '{0}{1}'.format(str(x)[2:],str(y)[:2])

Now, this an example and what I really have is a long and messy string, and so I want to put slicing inside the {}. I've studied the docs, but I can't figure out the correct syntax. My question is: is it possible to slice strings inside a replacement field?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

No, you can't apply slicing to strings inside a the replacement field.

You'll need to refer to the Format Specification Mini-Language; it defines what is possible. This mini language defines how you format the referenced value (the part after the : in the replacement field syntax).


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

...