简体   繁体   English

如何在未来使它变得更Python化或更具可读性?

[英]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 ). 我有一个由_的多个单词的字符串(例如hello_my_name_is_john_doe_good_day )。 I want to take this string and convert it to look like John Doe . 我想把这个字符串转换成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? 谁能提出一些建议,说明我如何清理它,使其在将来变得更加Python化和易读?

We can use .title() for the processing of individual substrings, and use ' '.join(..) to join these together, like: 我们可以使用.title()来处理各个子字符串,并使用' '.join(..)将它们连接在一起,例如:

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: 由于子元素可能是单个单词,因此我们也可以使用.capitalize()

# 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. 不错的是,如果tempStr1包含多个元素,它也会添加这些单词,并用空格分隔。

Furthermore .title() and .capitalize() are also more safe than performing string operations manually: if the string is empty, then these will still work. 此外, .title().capitalize()也比手动执行字符串操作更安全:如果字符串为空,则它们仍将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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