Python串联和整数和

时间:2018-05-27 00:24:44

标签: python string printing sum concatenation

我想打印数字和一些字符串,如:

import UIKit

var selectedHobbies : [String] = [] //Hold a global value of the 
selected hobbies
 var numberSelected:Int = 0 //Hold the number of selected hobbies


class TableViewController: UITableViewController, 
UISearchResultsUpdating {





var filteredHobbies = [String]() //The hobbies filted by the search bar
var searchController = UISearchController()
var resultController = UITableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.searchController = UISearchController(searchResultsController: resultController)
        tableView.tableHeaderView = self.searchController.searchBar

        self.searchController.searchResultsUpdater = self

        self.resultController.tableView.delegate = self
        self.resultController.tableView.dataSource = self



    }
    //updates search results according to what is in the search bar, filters hobbies out that dont contain the same string of text
    func updateSearchResults(for searchController: UISearchController) {
        self.filteredHobbies = hobbies.filter({ (hobbies: String) -> Bool in

            if hobbies.contains(searchController.searchBar.text!)
            {
                return true
            }
            else
            {
                return false
            }

        })

        self.resultController.tableView.reloadData()
    }




   // number of
    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1

    }
//swipe actions for table view
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            let important = importantAction(at: indexPath)
            return UISwipeActionsConfiguration(actions: [important])
    }
//takes the hobby according to the searched hobbies (if they are filtered)
func importantAction(at IndexPath: IndexPath) -> UIContextualAction {
    var hobby = ""
    if searchController.searchBar.text! == "" {
        hobby = hobbies[IndexPath.row]

    } else {
        hobby = filteredHobbies[IndexPath.row]
    }

    let action = UIContextualAction(style: .normal, title: "Important") { (action, view, completion) in
        completion(true)
    }
    // wont add hobbies otherwise
    if selectedHobbies.contains(hobby){
        action.title = "Add Hobby"
        action.backgroundColor = .gray

        print(selectedHobbies)
        return action

    }else {
    // adds hobbies if they arent in the array
        selectedHobbies.append(hobby)
        action.title = "Add Hobby"
        tableView.cellForRow(at: IndexPath)?.backgroundColor = UIColor.white
        action.backgroundColor = .green
        numberSelected += 1
        if numberSelected >= 10 {
            performSegue(withIdentifier: "segue1", sender: nil)
            print(selectedHobbies)
        }
        print(selectedHobbies)
        return action
    }
}
func removeAction(at IndexPath: IndexPath) -> UIContextualAction {
    var hobby = ""
    if searchController.searchBar.text! == "" {
        hobby = hobbies[IndexPath.row]
    } else {
        hobby = filteredHobbies[IndexPath.row]
    }

    let action = UIContextualAction(style: .normal, title: "Important") { (action, view, completion) in
        completion(true)
    }
    if selectedHobbies.contains(hobby){ //removes hobby if in selected hobbies

        selectedHobbies = selectedHobbies.filter{$0 != hobby}
        action.title = "Remove Hobby"
        action.backgroundColor = .red
        numberSelected -= 1

        print(selectedHobbies)
        return action
    }else {
        action.title = "Remove Hobby"
        action.backgroundColor = .gray
        print(selectedHobbies)
        return action
    }
}

override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let remove = removeAction(at: indexPath)
    return UISwipeActionsConfiguration(actions: [remove])
}

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


        if tableView == resultController.tableView
        {
            return self.filteredHobbies.count
        }
        else
        {
            return self.hobbies.count
        }

    }



    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell()


        if tableView == resultController.tableView
        {

            cell.textLabel?.text = self.filteredHobbies [indexPath.row]
        }
        else
        {
            cell.backgroundColor = UIColor.cyan
            cell.textLabel?.text = self.hobbies[indexPath.row]
        }



        return cell




    }


 }

这里" root"," left"和"总和"是字符串,其中rootLeaf和leftleaf是整数,我想找到它们的总和。

我检查了post here,但我无法实现整数的总和 (字符串连接中的数学运算)

4 个答案:

答案 0 :(得分:4)

rootLeaf = 4
leftLeaf = 8
print("root: " + str(rootLeaf)+ " left: " + str(leftLeaf) + " sum: {}".format(rootLeaf + leftLeaf))

这是你的输出:

root: 4 left: 8 sum: 12

在Python中,为了打印整数,必须先将它们转换为字符串。 .format方法允许您将整数参数(两个叶子的总和)转换为字符串。您在需要字符串{}的位置输入占位符,然后在.format方法中指定该整数将是什么。在这种情况下,rootLeaf + leftLeaf。

答案 1 :(得分:1)

如果您使用的是Python 3,则可以尝试使用.format

print("root: {0} left: {1} sum: {2}".format(rootLeaf, leftLeaf, rootLeaf+leftLeaf))

或者:

print("root: {}".format(rootLeaf), "left: {}".format(leftLeaf) , "sum: {}".format(rootLeaf+leftLeaf))

对于旧版本的Python,您可以尝试使用%

# '+' can be replaced by comma as well
print("root: %s" % rootLeaf + " left: %s" % leftLeaf + " sum: %s" %(rootLeaf+leftLeaf)) 

或者:

print("root: %s left: %s sum: %s" % (rootLeaf, leftLeaf, rootLeaf+leftLeaf))

答案 2 :(得分:0)

使用格式应该可以轻松处理所有类型。

print("root: {} left: {} sum: {}".format(rootLeaf, rootRight, rootLeaf + rootRight))

一般来说,请查看此网站以获取更多详细信息:https://pyformat.info/

答案 3 :(得分:0)

您正在获取TypeError,因为您正在使用整数连接字符串。首先需要将整数转换为字符串。您可以使用str函数执行此操作。

在这种情况下

{{1}}

将打印您想要的内容。