Coding Bash vs. Perl vs. Python (by Evan Liu)


Topics about string

String: Create multi-line string


		  
		  

Tasks:
1.Create a multi-line string
2.Print the string
		  
Bash Perl Python
  1. #1.Create a multi-line string
  2. read -r -d '' mstr <<'EOD'
  3. This is a string with muliple lines
  4. escaple exmaple: "hello\nworld!"
  5. Variable examples: $PS1, $SHELL, $USER, $$
  6. DIR=$(pwd)
  7. list or array examples: @list
  8. hash examples: %map
  9. EOD
  10. #2.Print the string
  11. echo "\$mstr=$mstr"
  12. -------output----------
  1. #1.Create a multi-line string
  2. #2.Print the string
  3. $mstr=This is a string with muliple lines
  4. escaple exmaple: "hello\nworld!"
  5. Variable examples: $PS1, $SHELL, $USER, $$
  6. DIR=$(pwd)
  7. list or array examples: @list
  8. hash examples: %map
  1. #1.Create a multi-line string
  2. my $mstr = <<'EOD';
  3. This is a string with muliple lines
  4. escaple exmaple: "hello\nworld!"
  5. Variable examples: $PS1, $SHELL, $USER, $$
  6. DIR=$(pwd)
  7. list or array examples: @list
  8. hash examples: %map
  9. EOD
  10. #2.Print the string
  11. print "\$mstr=$mstr\n";
  12. -------output----------
  1. #1.Create a multi-line string
  2. #2.Print the string
  3. $mstr=This is a string with muliple lines
  4. escaple exmaple: "hello\nworld!"
  5. Variable examples: $PS1, $SHELL, $USER, $$
  6. DIR=$(pwd)
  7. list or array examples: @list
  8. hash examples: %map
  1. #1.Create a multi-line string
  2. mstr = r'''This is a string with muliple lines
  3. escaple exmaple: "hello\nworld!"
  4. Variable examples: $PS1, $SHELL, $USER, $$
  5. DIR=$(pwd)
  6. list or array examples: @list
  7. hash examples: %map'''
  8. #2.Print the string
  9. print "mstr=%s\n"% mstr
  10. -------output----------
  1. #1.Create a multi-line string
  2. #2.Print the string
  3. mstr=This is a string with muliple lines
  4. escaple exmaple: "hello\nworld!"
  5. Variable examples: $PS1, $SHELL, $USER, $$
  6. DIR=$(pwd)
  7. list or array examples: @list
  8. hash examples: %map

String: Get the length of a string


		  
		  

Tasks:
1.Assign a string to a variable
2.Get the length of the string
		  
Bash Perl Python
  1. #1.Assign a string to a variable
  2. name="Scarborough Fair"
  3. #2.Get the length of the string
  4. echo ${#name}
  5. -------output----------
  1. #1.Assign a string to a variable
  2. #2.Get the length of the string
  3. 16
  1. #1.Assign a string to a variable
  2. $name="Scarborough Fair";
  3. #2.Get the length of the string
  4. print length($name)."\n";
  5. -------output----------
  1. #1.Assign a string to a variable
  2. #2.Get the length of the string
  3. 16
  1. #1.Assign a string to a variable
  2. name="Scarborough Fair"
  3. #2.Get the length of the string
  4. print len(name)
  5. -------output----------
  1. #1.Assign a string to a variable
  2. #2.Get the length of the string
  3. 16

String: Get a substring at a given index


		  
		  

Tasks:
1.Assign a string to a variable.
2.Print 5 chars starting from index 6, the output should be "rough".
		  
Bash Perl Python
  1. #1.Assign a string to a variable.
  2. name="Scarborough Fair"
  3. #2.Print 5 chars starting from index 6, the output should be "rough".
  4. echo "substr: ${name:6:5}"
  5. -------output----------
  1. #1.Assign a string to a variable.
  2. #2.Print 5 chars starting from index 6, the output should be rough.
  3. substr: rough
  1. #1.Assign a string to a variable.
  2. $name="Scarborough Fair";
  3. #2.Print 5 chars starting from index 6, the output should be "rough".
  4. print "substr: ".substr($name,6,5)."\n";
  5. -------output----------
  1. #1.Assign a string to a variable.
  2. #2.Print 5 chars starting from index 6, the output should be "rough".
  3. substr: rough
  1. #1.Assign a string to a variable.
  2. name="Scarborough Fair"
  3. #2.Print 5 chars starting from index 6, the output should be "rough".
  4. print "slicing:", name[6:11]
  5. -------output----------
  1. #1.Assign a string to a variable.
  2. #2.Print 5 chars starting from index 6, the output should be "rough".
  3. slicing: rough

String: Get index of a substring


		  
		  

Tasks:
1.test1
2.Assign a string to a variable.
3.Print index of substring "rough".
4.Check if substring "rough" exists or not.
		  
Bash Perl Python
  1. #1.test1
  2. name="Scarborough Fair"
  3. #2.Assign a string to a variable.
  4. x=${name%%rough*}
  5. echo -n "The index of 'rough' is: "
  6. [[ $x = $name ]] && echo -1 || echo ${#x}
  7. #3.Print index of substring "rough".
  8. padding=`grep -q rough <<<"$name"|| echo not`
  9. echo "'rough' does $padding exist in string \"$name\""
  10. -------output----------
  1. #1.test1
  2. #2.Assign a string to a variable.
  3. The index of 'rough' is: 6
  4. #3.Print index of substring rough.
  5. 'rough' does exist in string "Scarborough Fair"
  1. #1.test1
  2. $name="Scarborough Fair";
  3. #2.Assign a string to a variable.
  4. printf "The index of 'rough': %d\n", index($name,'rough');
  5. #3.Print index of substring "rough".
  6. printf "'rough' does%s exist in string Scarborough Fair", ( index($name,'rough') == -1 )? " not": "";
  7. -------output----------
  1. #1.test1
  2. #2.Assign a string to a variable.
  3. The index of 'rough': 6
  4. #3.Print index of substring "rough".
  5. 'rough' does exist in string Scarborough Fair
  1. #1.test1
  2. name="Scarborough Fair"
  3. #2.Assign a string to a variable.
  4. # get exception if none found with index()
  5. print "The index of 'rough':", name.index('rough')
  6. print "The index of 'rough':", name.find('rough')
  7. #3.Print index of substring "rough".
  8. print "'rough' does "+ ('' if 'rough' in name else 'not') + "exist in string "+name
  9. -------output----------
  1. #1.test1
  2. #2.Assign a string to a variable.
  3. # get exception if none found with index()
  4. The index of 'rough': 6
  5. The index of 'rough': 6
  6. #3.Print index of substring "rough".
  7. 'rough' does exist in string Scarborough Fair

String: Replace a substring


		  
		  

Tasks:
1.Assign a string to a variable
2.Replace 'Fair' with 'fair' for one occurrence
3.Replace 'Fair' with 'fair' for all occurrences
		  
Bash Perl Python
  1. #1.Assign a string to a variable
  2. name="Scarborough Fair Fair"
  3. #2.Replace 'Fair' with 'fair' for one occurrence
  4. echo ${name/Fair/fair}
  5. #3.Replace 'Fair' with 'fair' for all occurrences
  6. echo ${name//Fair/fair}
  7. -------output----------
  1. #1.Assign a string to a variable
  2. #2.Replace 'Fair' with 'fair' for one occurrence
  3. Scarborough fair Fair
  4. #3.Replace 'Fair' with 'fair' for all occurrences
  5. Scarborough fair fair
  1. #1.Assign a string to a variable
  2. $name="Scarborough Fair Fair";
  3. #2.Replace 'Fair' with 'fair' for one occurrence
  4. $name =~ s/Fair/fair/;
  5. printf $name."\n";
  6. #3.Replace 'Fair' with 'fair' for all occurrences
  7. $name="Scarborough Fair Fair";
  8. $name =~ s/Fair/fair/g;
  9. printf $name."\n";
  10. -------output----------
  1. #1.Assign a string to a variable
  2. #2.Replace 'Fair' with 'fair' for one occurrence
  3. Scarborough fair Fair
  4. #3.Replace 'Fair' with 'fair' for all occurrences
  5. Scarborough fair fair
  1. #1.Assign a string to a variable
  2. name="Scarborough Fair Fair"
  3. #2.Replace 'Fair' with 'fair' for one occurrence
  4. print name.replace('Fair','fair', 1)
  5. #3.Replace 'Fair' with 'fair' for all occurrences
  6. print name.replace('Fair','fair')
  7. -------output----------
  1. #1.Assign a string to a variable
  2. #2.Replace 'Fair' with 'fair' for one occurrence
  3. Scarborough fair Fair
  4. #3.Replace 'Fair' with 'fair' for all occurrences
  5. Scarborough fair fair

String: Capitalize a string


		  
		  

Tasks:
1.Assign a string to a variable
2.Change the string to Upper case 
		  
Bash Perl Python
  1. #1.Assign a string to a variable
  2. name="Scarborough Fair"
  3. #2.Change the string to Upper case
  4. echo $name | tr '[:lower:]' '[:upper:]'
  5. echo $name | tr '[:upper:]' '[:lower:]'
  6. # in awk
  7. echo $name | awk '{print toupper($0)}'
  8. echo $name | awk '{print tolower($0)}'
  9. # in bash 4.0
  10. echo ${name^^}
  11. echo ${name,,}
  12. echo ${name^}
  13. -------output----------
  1. #1.Assign a string to a variable
  2. #2.Change the string to Upper case
  3. SCARBOROUGH FAIR
  4. scarborough fair
  5. # in awk
  6. SCARBOROUGH FAIR
  7. scarborough fair
  8. # in bash 4.0
  9. SCARBOROUGH FAIR
  10. scarborough fair
  11. Scarborough Fair
  1. #1.Assign a string to a variable
  2. $name="Scarborough Fair";
  3. #2.Change the string to Upper case
  4. print uc($name)."\n";
  5. print lc($name)."\n";
  6. print ucfirst($name)."\n";
  7. print lcfirst($name)."\n";
  8. -------output----------
  1. #1.Assign a string to a variable
  2. #2.Change the string to Upper case
  3. SCARBOROUGH FAIR
  4. scarborough fair
  5. Scarborough Fair
  6. scarborough Fair
  1. #1.Assign a string to a variable
  2. name="Scarborough Fair"
  3. #2.Change the string to Upper case
  4. print name.upper()
  5. print name.lower()
  6. print name.capitalize()
  7. print name.title()
  8. -------output----------
  1. #1.Assign a string to a variable
  2. #2.Change the string to Upper case
  3. SCARBOROUGH FAIR
  4. scarborough fair
  5. Scarborough fair
  6. Scarborough Fair

String: Check if a variable is empty

In perl
Values are considered false if it equals '', (), [], {}, 0, 0L, 0.0, 0j, False, None

Tasks:
1.Define a function to check if the input is an empty string
2.Call the function with different arguments
		  
Bash Perl Python
  1. #1.Define a function to check if the input is an empty string
  2. func1(){
  3. s=$1
  4. if [ "$s" ]; then e1=" not"; fi
  5. if [ "$s" != "" ]; then e2=" not"; fi
  6. if [ -n "$s" ]; then e3=" not"; fi
  7. if [ ! -z "$s" ]; then e4=" not"; fi
  8. echo "\$1 is$e1 empty"
  9. echo "\$1 is$e2 empty"
  10. echo "\$1 is$e3 empty"
  11. echo "\$1 is$e4 empty"
  12. }
  13. #2.Call the function with different arguments
  14. #2.Call the function with different arguments
  15. func1
  16. #2.Call the function with different arguments
  17. func1 ""
  18. #2.Call the function with different arguments
  19. func1 " "
  20. -------output----------
  1. #1.Define a function to check if the input is an empty string
  2. #2.Call the function with different arguments
  3. #2.Call the function with different arguments
  4. $1 is empty
  5. $1 is empty
  6. $1 is empty
  7. $1 is empty
  8. #2.Call the function with different arguments
  9. $1 is empty
  10. $1 is empty
  11. $1 is empty
  12. $1 is empty
  13. #2.Call the function with different arguments
  14. $1 is not empty
  15. $1 is not empty
  16. $1 is not empty
  17. $1 is not empty
  1. #1.Define a function to check if the input is an empty string
  2. sub func1{
  3. $e1=$e2=1; #1 is true
  4. if(not defined $_[0]){ $e1=0 }
  5. if( $_[0] eq ""){ $e2=0 }
  6. print "argument ".(($e1)? "":"not ")."defined\n";
  7. print "argument ".(($e2)? "not ":"")."empty\n";
  8. }
  9. #2.Call the function with different arguments
  10. func1();
  11. # call with func1('')
  12. func1("");
  13. # call with func1(' ')
  14. func1(" ");
  15. -------output----------
  1. #1.Define a function to check if the input is an empty string
  2. #2.Call the function with different arguments
  3. argument not defined
  4. argument empty
  5. # call with func1('')
  6. argument defined
  7. argument empty
  8. # call with func1(' ')
  9. argument defined
  10. argument not empty
  1. #1.Define a function to check if the input is an empty string
  2. def func(p1):
  3. print "It's "+("not " if p1 else "")+"empty"
  4. print "It's "+("" if not p1 else "not ")+"empty"
  5. #2.Call the function with different arguments
  6. # ERROR: func() takes exactly 1 argument (0 given)
  7. # func()
  8. # call with func('')
  9. func('')
  10. # call with func(' ')
  11. func(' ')
  12. -------output----------
  1. #1.Define a function to check if the input is an empty string
  2. #2.Call the function with different arguments
  3. # ERROR: func() takes exactly 1 argument (0 given)
  4. # func()
  5. # call with func('')
  6. It's empty
  7. It's empty
  8. # call with func(' ')
  9. It's not empty
  10. It's not empty

String: Remove leading and tailing whitespaces

Note: Ip perl, chomp() function will remove current value of $/ at the end of a string. $/ defaults to a newline.

Tasks:
1.Define a variable with white spaces in value
2.Remove the whilespaces in the variable
3.output the result
		  
Bash Perl Python
  1. #1.Define a variable with white spaces in value
  2. s=" \t how to trim a string \t"
  3. echo -e "'$s'"
  4. #2.Remove the whilespaces in the variable
  5. s2=`echo -e "$s" |sed "s/^[[:space:]]*\|[[:space:]]*$//g"`
  6. s3=`echo -e "$s" |sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g'`
  7. #3.output the result
  8. echo -e "'$s2'"
  9. echo -e "'$s3'"
  10. -------output----------
  1. #1.Define a variable with white spaces in value
  2. ' how to trim a string '
  3. #2.Remove the whilespaces in the variable
  4. #3.output the result
  5. 'how to trim a string'
  6. 'how to trim a string'
  1. #1.Define a variable with white spaces in value
  2. $_=" \t how to trim a string \t";
  3. print "'".$_."'\n";
  4. #2.Remove the whilespaces in the variable
  5. s/^[[:space:]]*|[[:space:]]*$//g;
  6. #3.output the result
  7. print "'".$_."'";
  8. -------output----------
  1. #1.Define a variable with white spaces in value
  2. ' how to trim a string '
  3. #2.Remove the whilespaces in the variable
  4. #3.output the result
  5. 'how to trim a string'
  1. #1.Define a variable with white spaces in value
  2. s=" \t how to trim a string \t"
  3. print "'%s'" %s
  4. #2.Remove the whilespaces in the variable
  5. s2=s.strip()
  6. import re
  7. s3=re.sub(r'^\s*|\s*$',r'',s)
  8. #3.output the result
  9. print "'%s'" % s2
  10. print "'%s'" % s3
  11. -------output----------
  1. #1.Define a variable with white spaces in value
  2. ' how to trim a string '
  3. #2.Remove the whilespaces in the variable
  4. #3.output the result
  5. 'how to trim a string'
  6. 'how to trim a string'

String: Concatenate two strings


		  
		  

Tasks:
1.Assign a string to a variable.
2.Catenate two strings and print the result.
		  
Bash Perl Python
  1. #1.Assign a string to a variable.
  2. name="Scarborough Fair"
  3. #2.Catenate two strings and print the result.
  4. echo "hello, $name"
  5. printf "hello, %s\n" "$name"
  6. -------output----------
  1. #1.Assign a string to a variable.
  2. #2.Catenate two strings and print the result.
  3. hello, Scarborough Fair
  4. hello, Scarborough Fair
  1. #1.Assign a string to a variable.
  2. $name="Scarborough Fair";
  3. #2.Catenate two strings and print the result.
  4. print "hello, $name\n";
  5. # using dot operator
  6. print "hello, ".$name."\n";
  7. # using join function
  8. print join(" ","hello",$name);
  9. printf "hello, %s\n", "$name";
  10. -------output----------
  1. #1.Assign a string to a variable.
  2. #2.Catenate two strings and print the result.
  3. hello, Scarborough Fair
  4. # using dot operator
  5. hello, Scarborough Fair
  6. # using join function
  7. hello Scarborough Fairhello, Scarborough Fair
  1. #1.Assign a string to a variable.
  2. name="Scarborough Fair"
  3. #2.Catenate two strings and print the result.
  4. print "hello, "+name
  5. print "hello,", name
  6. print "hello, %s" % (name)
  7. -------output----------
  1. #1.Assign a string to a variable.
  2. #2.Catenate two strings and print the result.
  3. hello, Scarborough Fair
  4. hello, Scarborough Fair
  5. hello, Scarborough Fair

String: Split string into array


		  
		  

Tasks:
1.Define a variable with string value
2.Get and output the array
		  
Bash Perl Python
  1. #1.Define a variable with string value
  2. str="bing.com|google.com|baidu.com|yahoo.com"
  3. #2.Get and output the array
  4. IFS='|' sites=(`echo $str`)
  5. echo "${sites[@]}"
  6. unset IFS
  7. -------output----------
  1. #1.Define a variable with string value
  2. #2.Get and output the array
  3. bing.com google.com baidu.com yahoo.com
  1. #1.Define a variable with string value
  2. $str="bing.com|google.com|baidu.com|yahoo.com";
  3. #2.Get and output the array
  4. @sites=split(/\|/,$str);
  5. print "@sites";
  6. -------output----------
  1. #1.Define a variable with string value
  2. #2.Get and output the array
  3. bing.com google.com baidu.com yahoo.com
  1. #1.Define a variable with string value
  2. str="bing.com|google.com|baidu.com|yahoo.com"
  3. #2.Get and output the array
  4. sites=str.split('|')
  5. print sites
  6. -------output----------
  1. #1.Define a variable with string value
  2. #2.Get and output the array
  3. ['bing.com', 'google.com', 'baidu.com', 'yahoo.com']