[英]How do I print the first letter and second letter and third.. of each string in python?
如果我輸入:'I love stack overflow',我如何從這個字符串中打印第一個&第二個&第三個字母。
output 是這樣的:
'Ilso'、'otv'、'vae'、'ecr'...
如果有人可以幫助我,那就太好了:謝謝:D
使用str.split
、 str.join
和itertools.zip_longest
:
from itertools import zip_longest
s = 'I love stack overflow'
result = [''.join(chars) for chars in zip_longest(*s.split(), fillvalue='')]
print(result)
# ['Ilso', 'otv', 'vae', 'ecr', 'kf', 'l', 'o', 'w']
s.split()
將字符串拆分為單詞list
,以空格分隔。 zip_longest
返回所有單詞的字符元組,用空字符串''
填充缺失值(對於短單詞)。 ''.join()
將字符連接(添加)到新字符串。 列表理解循環遍歷所有的字母元組、第一個字母、第二個字母等。
string = 'I love stack overflow'
words = string.split()
longest_word = len(max(words, key=len))
result = [
''.join([
word[index]
for word in words
if len(word) > index
])
for index in range(longest_word)
]
print(result)
這可以是解決方案
a='I love stack overflow'
l=a.split()
for i in range(len(max(l,key=len))):
b=''
for j in l:
try:
b=b+j[i]
except Exception:
pass
print(b)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.