如何从特殊角度切弦

时间:2019-06-26 13:42:28

标签: python string

我有一些汽车名称,例如:

Mercedes-Benz C-Class C180 CGI,
BMW 3 Series 318i (New 5-yr COE),
Kia Cerato Forte 1.6M EX (COE till 03/2024) ...

我想放出这样的东西:

Mercedes-Benz C-Class, 
BMW 3, 
Kia Cerato ...

我的意思是前两个部分。我尝试了下面的代码,它可以工作,但是我想知道什么是更好的方法以及我的问题:

In [21]: car = 'Mercedes-Benz C-Class C180 CGI'
In [22]: s = car.find(' ')
In [23]: car_1 = car[:s]
In [24]: car_2 = car[s+1:]
In [25]: s_2 = car_2.find(' ')
In [26]: car_3 = car_2[:s_2]
In [27]: car_name = car_2+' '+car_3
In [28]: car_name = car_1+' '+car_3
In [29]: car_name
Out[29]: 'Mercedes-Benz C-Class'

3 个答案:

答案 0 :(得分:4)

要获取字符串中的前两个部分,并用空格分隔各部分,请使用.split().join()

>>> s = "This sentence is a sample sentence."
>>> " ".join(s.split()[:2])
"This sentence"

答案 1 :(得分:2)

简单的列表理解就可以了

car_list=[
'Mercedes-Benz C-Class C180 CGI',
'BMW 3 Series 318i (New 5-yr COE)',
'Kia Cerato Forte 1.6M EX (COE till 03/2024)']

[' '.join(car.split(" ",2)[:2]) for car in car_list]

输出:

['Mercedes-Benz C-Class', 'BMW 3', 'Kia Cerato']

答案 2 :(得分:1)

您可以在空间的基础上分割值,然后将前两个索引以空格分隔以获取所需的输出

 appBar: AppBar(
    centerTitle: true,
    title: Text('hehe',
    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25.0),),
    actions: <Widget>[
      Padding(
        padding: const EdgeInsets.only(right: 10.0),
        child: IconButton(icon: Icon(Icons.comment),
            onPressed: () {
          showDialog(context: context,
          builder: (BuildContext context){
            return AlertDialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
              content: Form(key: formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.all(8.0),
                    child: TextFormField(
                      initialValue: '',
                      onSaved: (val) => board.subject = val,
                      validator: (val) => val == "" ? val: null,
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.all(8.0),
                    child: RaisedButton(
                      color: Colors.indigo,
                      child: Text(
                          'Post',
                      style: TextStyle(color: Colors.white),),
                      onPressed: () {
                        handleSubmit();
                        Navigator.of(context).pop();
                      },
                    ),
                  )
                ],
              ),
              ),
            );
          },
          );
            }
            ),
      ),
    ],
  ),

希望这会有所帮助。