简体   繁体   English

如何将一定长度后的字符串中的所有内容移动到列表中 python

[英]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'.我正在尝试构建一个 function,它会将 140 个字符后的所有内容都放入一个字符串中,并将其移动到一个新变量中以用于第二个“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?我需要能够引用索引值为 140-280 的列表中的所有内容,但是当它是一个字符串时我似乎不能这样做?

Since you are using python, you don't have to loop through a string.由于您使用的是 python,因此您不必遍历字符串。 Your code can be as simple as (assuming your input is at most 280, as you do in your original example):您的代码可以很简单(假设您的输入最多为 280,就像您在原始示例中所做的那样):

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.只需从 position 140 开始制作一个 substring。

In snippet below "sub_s" will have the value "fg"在下面的代码片段中,“sub_s”的值为“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通过这种方式,输入字符串可以是任意长度,生成器将返回最多 MAXTWEET 长度的字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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