在Python中重写大小写字符串

2024-04-23 07:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Phyton很陌生,所以我要你帮忙。 关于字符串,可以使用s=s.upper()编写大写字符,使用s=s.lower()编写小写字符。你知道吗

但是如何重写给定的字符串,使前五个字符为大写,后五个字符为小写,依此类推,最后用10个字符的宽度写字符串长度?你知道吗


Tags: 字符串宽度字符upperlower小写大写个字符
2条回答

这里有一个简单的方法来获取一个字符串,将它的前5个字母改为大写,并将后面的所有字母改为小写。你不必为此导入任何库。你知道吗

string = "abcdefghij"

string1 = string[:5]

string2 = string[5:]

stringfinal = string1.upper() + string2.lower()

print(stringfinal)
print(len(stringfinal))

在Python2.7中试试这个

from __future__ import print_function
s='stackoverflow'
for i in range(0,len(s),5):
      if (int(i%2) == 0):
            print ( s[i:i+5].lower() ,end = "")
      else:
            print (s[i:i+5].upper(),end = "")
#If you want 10 spaces before displaying lenght
print (" "*10 ,end = " ")
print (len(s))

#if you want to reserve 10digits for displaying length replace last two lines with below  line
print ("%10d" %(len(s)))

相关问题 更多 >