编写一个 Python 程序,使用内置函数、for 循环、while 循环和 ASCII 示例将字符串转换为大写。
使用 upper 函数转换字符串
此 Python 程序允许用户输入一个字符串。接下来,我们使用内置的字符串函数将字符串中的小写字母转换为大写字母。
提示:请参阅 字符串 文章,以了解 Python 中有关字符串的所有信息。
tx1 = input("Please Enter your Own Text : ")
tx2 = tx1.upper()
print("\nOriginal = ", tx1)
print("Result = ", tx2)
将字符串转换为大写的输出
Please Enter your Own Text : Code Example
Original = Code Example
Result = CODE EXAMPLE
Python 使用 For 循环将字符串转换为大写
此 Python 程序 允许用户输入一个字符串。接下来,它查找小写字母并将其转换为大写。
首先,我们使用 For 循环 迭代字符串中的字符。在 For 循环内部,我们使用 If Else 语句检查字符是否在 a 和 z 之间。如果为真,我们将从其 ASCII 值中减去 32。否则,我们将该字符复制到 string 1。
提示:请参阅 查找字符串中总字符的 ASCII 值 文章和 ASCII 表 以了解 ASCII 值。
tsm = input("Please Enter your Own Text : ")
tsm1 = ''
for i in range(len(tsm)):
if(tsm[i] >= 'a' and tsm[i] <= 'z'):
tsm1 = tsm1 + chr((ord(tsm[i]) - 32))
else:
tsm1 = tsm1 + tsm[i]
print("\nOriginal Words = ", tsm)
print("The Result of them = ", tsm1)
Please Enter your Own Text : Learn
Original Words = Learn
The Result of them = LEARN
使用 While 循环
此 Python 小写转大写转换程序与上述程序相同。但是,我们只是将 For 循环替换为 While 循环。
txt = input("Please Enter your Own Text : ")
txt1 = ''
i = 0
while(i < len(txt)):
if(txt[i] >= 'a' and txt[i] <= 'z'):
txt1 = txt1 + chr((ord(txt[i]) - 32))
else:
txt1 = txt1 + txt[i]
i = i + 1
print("\nActual Word = ", txt)
print("The Result = ", txt1)
Please Enter your Own Text : Tutorial GAtewAy
Actual Word = Tutorial GAtewAy
The Result = TUTORIAL GATEWAY
Python 程序将小写字符串转换为大写示例 4
此字符串大写程序与第二个示例相同。但是,我们正在将 For 循环与对象一起使用
smp = input("Please Enter your Own Words : ")
smp1 = ''
for i in smp:
if(i >= 'a' and i <= 'z'):
smp1 = smp1 + chr((ord(i) - 32))
else:
smp1 = smp1 + i
print("\nOriginal = ", smp)
print("The Result = ", smp1)

使用 ASCII 值转换大写
在此程序中,我们比较 ASCII 值以检查字符串中是否存在任何小写字母。如果为真,我们将它们转换为大写。
stp = input("Please Enter your Own Text : ")
stp1 = ''
for i in stp:
if(ord(i) >= 97 and ord(i) <= 122):
stp1 = stp1 + chr((ord(i) - 32))
else:
stp1 = stp1 + i
print("\nActual = ", stp)
print("The Result = ", stp1)
Please Enter your Own Text : Sample InformatIon
Actual = Sample InformatIon
The Result = SAMPLE INFORMATION