如何在句子中的每个单词前面加一个字符,直到达到句子中最大单词的长度



在列出句子单词后,我试图迭代句子中的每个单词,并添加"l",直到每个单词中的字符长度达到最大单词的长度。但是使用while循环,它表示对象没有长度。

def convert_string(ip):
ip_list = ip.split()
print(ip_list)
max_length = max(len(w) for w in ip_list)
for w in range(len(ip_list)):
while(len(w) < max_length):
print(w)
w = 'l'+w
return str(ip)

您的问题在于语句for w in range(len(ip_list)):。在这种情况下,w是一个整数值,在下一行中,您试图找到len(w(,这会引发一个错误。要解决问题,请将语句for w in range(len(ip_list)):替换为for w in ip_list:

在@goodeejay的回答和我之前的回答的基础上,这就是如何解决你的问题。

sentence = 'Now is the time for all good country men to come to the aide of their country'
def convert_string(ip):
ip_list = ip.split()
rslt = []
max_length = max(len(w) for w in ip_list)
for w in ip_list:
rslt.append(w.rjust(max_length, '1'))
return ' '.join(rslt)  
convert_string(sentence)  

收益率:

'1111Now 11111is 1111the 111time 1111for 1111all 111good country 1111men 11111to 111come 11111to 1111the 111aide 11111of 11their country'

str类型的内置rjustljust方法,用于填充具有指定填充字符的字符串

示例:

string = "192.168.0.1"
new_str = string.rjust(20, "l")

输出:

lllllllll192.168.0.1

最新更新