Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

String and Characters



In Python, a string is a sequence of characters, and both string and character are considered the same. Python does not have a data type with respect to characters. Therefore, we can use a single-character string for characters.

A string is a sequence of characters and can include text and numbers. String values must be enclosed in matching single quotes 'I am a string' or double quotes "I am also a string".
  
 	a = 'I am a string'
  	b = "I am also a string"
  
  

Encoding

As computers only recognize binary codes (i.e., a sequence of 0/1s), a character must be converted into binary numbers in a computer. Mapping a character to its binary representation is called character encoding. 

There are different ways to encode a character such as ASCII (American Standard Code for Information Interchange) and Unicode. ASCII encodes 128 specified characters into seven-bit integers which you can find from the ASCII chart. Unicode is an encoding scheme for representing international characters. A Unicode starts with \u, followed by four hexadecimal digits that run from \u0000 to \uFFFF. 

As Python supports Unicode and you can try to print some Unicode characters.
  
  >>> print(u'\u6B22\u8FCE')
  欢迎
  
  
  
  >>> print(u'\u011f')
  ğ
  
  
Python's ord() function takes the string argument of a single Unicode character and return its integer Unicode code decimal value.
  
  >>> ord('ğ')
  287
  
  

Concatenation

You can concatenate two strings in Python simply using +, e.g., "welcome" + " to my blog".

  >>> a = 'welcome' + ' to my blog'
  >>> print(a)
  welcome to my blog
  


Why do we need both single and double quotes

You can concatenate two strings in Python simply using +, e.g., "welcome" + " to my blog".

>>> print('Alice says 'hello' to Bob')
  File stdin, line 1
    print('Alice says 'hello' to Bob')
                       ^
SyntaxError: invalid syntax
  
So we can use different quotes to achieve what we want.

  >>> print('Alice says "hello" to Bob')
  Alice says "hello" to Bob
  >>> print("Alice says 'hello' to Bob")
  Alice says 'hello' to Bob
  
In case you really want to stick to one quote, either single or double, you need to use add \ (backslash) to espcape

  >>> print("Alice says \"hello\" to Bob")
  Alice says "hello" to Bob
  
Some other special characters such as 
\' or \" include 
  • \' => ' 
  • \" => " 
  • \n => treated as newline 
  • \t => treated as tab
Although \n provides a way to change to new line, it is not so convinient for long text. 

>>> print('this is first line\nthis is second line\nthis is third line')
this is first line
this is second line
this is third line
Thanksfully, Python provides another special method to input long text

>>> print('''this is first line
... this is second line
... this is third line''')
this is first line
this is second line
this is third line

How to get tuple from a tuple string / How to convert a tuple string to tuple in Python

For example, we would like to get a tuple (1,2,3,4,5) out of a string - '(1,2,3,4,5)' in python. We can use literal_eval from ast as follows:

from ast import literal_eval
s = '(1,2,3,4,5)'
t = literal_eval(s)

Java - Count the number of times a word appears in a string


  • Apache Common StringUtils function

1:       public static int countMatches(String str, String sub) {  
2:         if (isEmpty(str) || isEmpty(sub)) {  
3:           return 0;  
4:         }  
5:         int count = 0;  
6:         int idx = 0;  
7:         while ((idx = str.indexOf(sub, idx)) != -1) {  
8:           count++;  
9:           idx += sub.length();  
10:         }  
11:         return count;  
12:       }  
13:       public static boolean isEmpty(String str) {  
14:     return str == null || str.length() == 0;  
15:    }  

  • Use Regex
1:       public static int countMatchesWithRegex(String str, String reg) {  
2:            Matcher m = Pattern.compile(reg).matcher(str);  
3:            int matches = 0;  
4:            while(m.find())  
5:              matches++;  
6:            return matches;  
7:       }  

  • Difference: Regex approach can get correct counting over "Africa" and "African"

1:            String target = "South Africa South African South Africa.";  
2:            System.out.println(StringUtils.countMatches(target, "South Africa")); // Return 3  
3:            System.out.println(StringUtils.countMatchesWithRegex(target, "\\bSouth African\\b")); // Return 1  

PHP function for removing URLs in string





While filtering URL information within tweet, function with regular expression to find and replace it is needed. The remove_URL() function below could do exactly what I want to do:)

PHP function for removing URLs in string:

1:  <?php  
2:  $string = "100% 준비되면 하겠다는 것은 하늘나라 가서 시작하겠다는 겁니다..http://t.co/S2sTmdF45o";  
3:  echo remove_URL($string);  
4:  function remove_URL($html){  
5:    return $result = preg_replace(  
6:      '%\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))%s',  
7:      '',  
8:      $html  
9:    );  
10:  }  
11:  ?>