Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to move everything in a string after a certain length into a list python

I am trying to build a function that will take everything in a string after 140 characters and move it into a new variable for a second ‘tweet’.

tweetlength = 140
tweet = input("What do you want to tweet: ")
tweet_copy = []
tweet_2 = []

for i in tweet:
    if len(tweet) <= tweetlength:
        print(tweet)
        break
    if len(tweet) >= tweetlength:
        tweet_copy = tweet
        for x in tweet_copy [140, 280]:
            tweet_2.append(x)
            print(tweet_copy + tweet_2)

However I am currently getting an error saying "string indices must be integers". I need to be able to refer to everything within the list with an index value of 140-280 but it seems I can’t do that while it’s a string?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since you are using python, you don’t have to loop through a string. Your code can be as simple as:

tweetlength = 140
tweet = input("What do you want to tweet: ")
tweet, tweet_2 = (tweet[:tweetlength], tweet[tweetlength:])
print(tweet)
if tweet_2:  # An empty string evaluates as False
    print('Second part')
    print(tweet_2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading