Nelson Wang
Nelson Wang

Reputation: 23

How I create a loop for adding words into string python

I was trying to learn python through creating script whenever it is necessary, even just for a simple math calculation for instance. So I want to create a automatic twitter paragraph separate-r, and perhaps read a .txt file and auto-twit, those are afterwords.

I had my logic use a loop. First, to count whether if the sentence needed to be separated into multiple ones. If so, it would be over 280 characters (twitter limit) it would use split to break it up, and then run the loop of appending 280 characters into a new string into a list.

Here is what I have got so far...sorry

longtext = input()

while True:

  if len(longtext) <= 280:
    print(len(longtext))
    break

  else:
    splited = longtext.split()
    new280 = []

    for i in range(len(splited)):

      if i % 280 == 0:
        new280.append()
        new280twiforcopy = ''.join(new280)

I know this is probably not good at all, but I am very much stucked...

For example:

input:

some kind of 400 words text string...
"xxx  * 400"

output:

"xxx *280"
"xxx *120"

(x means characters)

Upvotes: 1

Views: 1296

Answers (2)

RomainL.
RomainL.

Reputation: 1014

In python you can slice and index list

tot_length = len(longtext)

i = 0
increment = 280

while i < tot_length:
    print([longtext[i: i + increment]])
    i += increment

Upvotes: 1

Harshil
Harshil

Reputation: 1000

The following might help:

# consider my firstlist is made up of x*400
firstlist = 'x' * 400

if len(firstlist) <= 280:
  print(len(firstlist))
else:
  new280 = []
  while len(firstlist) > 280:
    new280.append(firstlist[:280])
    firstlist = firstlist[280:]
  new280.append(firstlist)

for i in new280:
  print(i)

Output:

xxx.... (280 times)

xxx.... (120 times)


You can test the code here.

Upvotes: 1

Related Questions