Reputation: 175
What I want to do?
I want to create a python program that takes a text file, makes the text into a list of strings like this
['Man', 'request', 'adapted', 'spirits', 'set', 'pressed.', 'Up', 'to']
(1)
, takes the number of letters of each word into a different list like this [3, 7, 7, 7, 3, 8, 2, 2]
(2)
and checks that if the number of each string element is greater than 3 (>3), removes its first letter and adds it to the end of the word with 'xy' string too. The result of the final list should be:
['Man', 'equestrxy', 'daptedaxy', 'piritssxy', 'set', 'ressed.pxy', 'Up', 'to']
(3)
What I have already done? I have made (1) and (2) parts of code and I am currently trying the (3) .
My code with comments:
text = open("RandomTextFile.txt").read().split() #this is the the part (1)
#function that creates the second part (2)
def map_(A):
return list(map(len, A))
words = map_(text) #list that contains the example list of (2)
#This is the part (3) and I try to achieve it by creating a loop
for i in range(y):
if words[i]>3:
text[i] = [x + string for x in text]
Can anyone suggest what I can do to achieve the part (3)? Thanks in advance!
Upvotes: 1
Views: 58
Reputation: 5949
For any word like this: t = 'request'
you can use slicing:
t[1:]+t[0]+'xy'
Upvotes: 1
Reputation: 2522
Using list comphrehension
>>> x = ['Man', 'request', 'adapted', 'spirits', 'set', 'pressed.', 'Up', 'to']
>>> [i[1:] + i[0] + 'xy' if len(i) > 3 else i for i in x]
['Man', 'equestrxy', 'daptedaxy', 'piritssxy', 'set', 'ressed.pxy', 'Up', 'to']
Upvotes: 2
Reputation: 99
You can do something like:
def format_strings(strs):
len_strs = [len(s) for s in strs]
return [strs[i][1:] + 'xy' if len_str > 3
else strs[i] for i, len_str in enumerate(len_strs)]
Upvotes: 1