[英]How to move everything in a string after a certain length into a list python
我正在嘗試構建一個 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)
但是,我目前收到一條錯誤消息,提示“字符串索引必須是整數”。 我需要能夠引用索引值為 140-280 的列表中的所有內容,但是當它是一個字符串時我似乎不能這樣做?
由於您使用的是 python,因此您不必遍歷字符串。 您的代碼可以很簡單(假設您的輸入最多為 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)
只需從 position 140 開始制作一個 substring。
在下面的代碼片段中,“sub_s”的值為“fg”
s = "abcdefg"
sub_s = s[5:]
我會使用這樣的生成器:
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)
通過這種方式,輸入字符串可以是任意長度,生成器將返回最多 MAXTWEET 長度的字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.