如何遍历字符串并将以某个字母开头的单词添加到空列表中?

时间:2018-09-21 12:10:45

标签: python loops startswith

因此,对于一项分配,我必须创建一个空列表变量empty_list = [],然后在字符串上进行python循环,然后将每个以't'开头的单词添加到该空列表中。我的尝试:

text = "this is a text sentence with words in it that start with letters"
empty_list = []
for twords in text:
    if text.startswith('t') == True:
        empty_list.append(twords)
    break
print(empty_list)

这仅打印一个[t]。我敢肯定我没有正确使用startswith()。我将如何正确执行这项工作?

4 个答案:

答案 0 :(得分:1)

text = "this is a text sentence with words in it that start with letters"
print([word for word in text.split() if word.startswith('t')])

答案 1 :(得分:0)

适用于您的解决方案。您还需要用text.startswith('t')替换twords.startswith('t'),因为您现在正在使用twords遍历存储在text中的原始语句的每个单词。您使用了break,这只会使代码打印this,因为找到第一个单词后,它将在for循环之外中断。要去除所有以t开头的单词,您需要摆脱break

text = "this is a text sentence with words in it that start with letters"
empty_list = []
for twords in text.split():
    if twords.startswith('t') == True:
        empty_list.append(twords)
print(empty_list)
> ['this', 'text', 'that']

答案 2 :(得分:0)

尝试这样的事情:

Date

text = "this is a text sentence with words in it that start with letters" t = text.split(' ') ls = [s for s in t if s.startswith('t')] 将成为结果列表

Python非常适合使用列表理解。

答案 3 :(得分:0)

下面的代码有效,

 public patientFormInit() {
    this.emrPatientdetailsForm = this.FB.group({
      Communicationx: this.FB.array([this.createCommunicationInformation()])
    });
    if (this.patientId) {
      this.getPateintBasicInfo();
    }
  }

    private createCommunicationInformation() {
    return this.FB.group({
      Language: [''],
      Preferred: [''],
      Communication: ['']
    })
  }

   private getPateintBasicInfo() {
    let params = { 'Id': this.userId }
    this.emrService.getEmrPatientBasicInfo(params).subscribe(pateintBasicInfoLists => {
      this.listPatientInfo = pateintBasicInfoLists.Body.Data[0];
      console.log(this.listPatientInfo[0].Communication);
      let res = pateintBasicInfoLists.Body.Data[0][0];
      this.emrPatientdetailsForm.patchValue({
        Communicationx: res.Communication
      })
    })
  }

您的代码中的问题是

  

您要遍历每个字母,这是错误的