用chr和ord大写每个单词

时间:2019-12-07 21:12:25

标签: python-3.x letter capitalize chr ord

首先,我必须从用户那里收到一个字符串。该函数将大写引入的字符串对象。它将使单词以大写字母开头,而所有其余字符都以小写字母开头。这是我所做的:

ssplit = s.split()
for z in s.split():
    if ord(z[0]) < 65 or ord(z[0])>90:
        l=(chr(ord(z[0])-32))
        new = l + ssplit[1:]
        print(new)
    else:
        print(s)

我看不到我在做错什么。

2 个答案:

答案 0 :(得分:1)

有许多python方法可以为您轻松解决此问题。例如,str.title()将大写给定字符串中每个单词的开头。如果要确保所有其他字母均为小写,则可以先执行str.lower(),然后执行str.title()

s = 'helLO how ARE YoU'
s.lower()
s.capitalize()
# s = 'Hello How Are You'

答案 1 :(得分:1)

使用@Pyer建议的str.title()很不错。如果需要使用chrord,则应正确设置变量-请参见代码中的注释

s = "this is a demo text"
ssplit = s.split()

# I dislike magic numbers, simply get them here:
small_a = ord("a") # 97
small_z = ord("z")

cap_a = ord("A")   # 65

delta = small_a - cap_a

for z in ssplit :  # use ssplit here - you created it explicitly
    if small_a <= ord(z[0]) <= small_z:
        l = chr(ord(z[0])-delta)
        new = l + z[1:]            # need z here - not ssplit[1:]
        print(new) 
    else:
        print(s)

输出:

This
Is
A
Demo
Text
相关问题