str.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright David Abrahams 2004. Distributed under the Boost
  2. // Software License, Version 1.0. (See accompanying
  3. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. #include <boost/python/module.hpp>
  5. #include <boost/assert.hpp>
  6. #include <boost/python/def.hpp>
  7. #include <boost/python/class.hpp>
  8. #include <boost/python/str.hpp>
  9. #define BOOST_ENABLE_ASSERT_HANDLER
  10. #include <boost/assert.hpp>
  11. using namespace boost::python;
  12. object convert_to_string(object data)
  13. {
  14. return str(data);
  15. }
  16. void work_with_string(object print)
  17. {
  18. str data("this is a demo string");
  19. print(data.split(" "));
  20. print(data.split(" ",3));
  21. print(str("<->").join(data.split(" ")));
  22. print(data.capitalize());
  23. print('[' + data.center(30) + ']');
  24. print(data.count("t"));
  25. #if PY_VERSION_HEX < 0x03000000
  26. print(data.encode("utf-8"));
  27. print(data.decode("utf-8"));
  28. #else
  29. print(data.encode("utf-8").attr("decode")("utf-8"));
  30. print(data.encode("utf-8").attr("decode")("utf-8"));
  31. #endif
  32. BOOST_ASSERT(!data.endswith("xx"));
  33. BOOST_ASSERT(!data.startswith("test"));
  34. print(data.splitlines());
  35. print(data.strip());
  36. print(data.swapcase());
  37. print(data.title());
  38. print("find");
  39. print(data.find("demo"));
  40. print(data.find("demo"),3,5);
  41. print(data.find(std::string("demo")));
  42. print(data.find(std::string("demo"),9));
  43. print("expandtabs");
  44. str tabstr("\t\ttab\tdemo\t!");
  45. print(tabstr.expandtabs());
  46. print(tabstr.expandtabs(4));
  47. print(tabstr.expandtabs(7L));
  48. print("operators");
  49. print( str("part1") + str("part2") );
  50. // print( str("a test string").slice(3,_) );
  51. // print( str("another test")[5] );
  52. print(data.replace("demo",std::string("blabla")));
  53. print(data.rfind("i",5));
  54. print(data.rindex("i",5));
  55. BOOST_ASSERT(!data.startswith("asdf"));
  56. BOOST_ASSERT(!data.endswith("asdf"));
  57. print(data.translate(str('a')*256));
  58. bool tmp = data.isalnum() || data.isalpha() || data.isdigit() || data.islower() ||
  59. data.isspace() || data.istitle() || data.isupper();
  60. (void)tmp; // ignored.
  61. }
  62. BOOST_PYTHON_MODULE(str_ext)
  63. {
  64. def("convert_to_string",convert_to_string);
  65. def("work_with_string",work_with_string);
  66. }
  67. #include "module_tail.cpp"