Keep uppercase after / in a string

。_饼干妹妹 提交于 2019-12-24 11:31:07

问题


I'm trying to title the following string:

"Men's L/S long sleeve"

I'm using string.capwords right now but it's not working as expected.

For example:

x = "Men's L/s Long Sleeve"
y = string.capwords(x)
print(y)

outputs:

Men's L/s Long Sleeve

but I want:

Men's L/S Long Sleeve (uppercased S after the /)

Is there an easy way to go about doing this?


回答1:


Split by /, then run capwords individually on all the components, then rejoin the components

text = "Men's L/s Long Sleeve"
"/".join(map(string.capwords, text.split("/")))
Out[10]: "Men's L/S Long Sleeve"



回答2:


You can split the string on '/', use string.capwords on each substring, and rejoin on '/':

import string

'/'.join(string.capwords(s) for s in "Men's L/S long sleeve".split('/'))



回答3:


It sounds like the / might not be a reliable indicator that a capital letter is needed. In case the more reliable indicator is actually that the letter was capitalised originally, you could try iterating through each string and only extracting the letters got promoted to upper:

import string
x = "Men's L/S long sleeve"
y = string.capwords(x)
z = ''
for i,l in enumerate(x):
    if(l.isupper()):
        z += l
    else:
        z += y[i]

So on strings like:

"brand XXX"
"shirt S/M/L"
"Upper/lower"

You'll get:

"Brand XXX"
"Shirt S/M/L"
"Upper/lower"

Which I think it probably more desirable than using the / as an indicator.



来源:https://stackoverflow.com/questions/56411174/keep-uppercase-after-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!