简体   繁体   中英

How to make this more Pythonic or readable for the future?

I have a string of multiple words connected with _ (for example hello_my_name_is_john_doe_good_day ). I want to take this string and convert it to look like John Doe .

I currently have

tempStr0 = "hello_my_name_is_john_doe_good_day"
tempStr1 = tempStr0.split("_")[4:6]
tempStr2 = (tempStr1[0][0].upper() + tempStr1[0][1:] + " " + tempStr1[1][0].upper() + tempStr1[1][1:])
print(tempStr2) 
# John Doe

This obviously does work but looks pretty ugly. Can anyone make some suggestions on how I might clean this up to make it more Pythonic and readable for the future?

We can use .title() for the processing of individual substrings, and use ' '.join(..) to join these together, like:

tempStr2 = ' '.join(sube.title() for sube in tempStr1)

this will capitalize every word. Since the subelements are probably individual words, we can use .capitalize() as well:

# alternative
tempStr2 = ' '.join(sube.capitalize() for sube in tempStr1)

The nice thing is that if tempStr1 contains multiple elements, it will add these words as well, separated by a space.

Furthermore .title() and .capitalize() are also more safe than performing string operations manually: if the string is empty, then these will still work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM