如何在句子中的每个单词前添加一个字符,直到达到句子中最大单词的长度?
How to add a character in front of each word in a sentence till it reaches the length of maximum sized word in the sentence?
我尝试在列出句子单词后遍历句子中的每个单词并添加 '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
类型有内置的rjust
和ljust
方法,用于用指定的填充字符填充字符串
示例:
string = "192.168.0.1"
new_str = string.rjust(20, "l")
输出:
lllllllll192.168.0.1
我尝试在列出句子单词后遍历句子中的每个单词并添加 '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
类型有内置的rjust
和ljust
方法,用于用指定的填充字符填充字符串
示例:
string = "192.168.0.1"
new_str = string.rjust(20, "l")
输出:
lllllllll192.168.0.1