简体   繁体   中英

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?

Since you are using python, you don't have to loop through a string. Your code can be as simple as (assuming your input is at most 280, as you do in your original example):

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)

Just make a substring starting at position 140.

In snippet below "sub_s" will have the value "fg"

s = "abcdefg"
sub_s = s[5:]

I would use a generator like this:

MAXTWEET = 140

def tweets(user_input):
  while user_input:
    yield user_input[:MAXTWEET]
    user_input = user_input[MAXTWEET:]

for tweet in tweets('A very long string'):
  print(tweet)

In this way the input string can be of any length and the generator will return strings of, at most, MAXTWEET length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM