Difference between revisions of "String Manipulation - Python"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(String Manipulation in Python)
(String Concatenation)
Line 38: Line 38:
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
 
str = 'Hello World!'  
 
str = 'Hello World!'  
print (str + "TEST“) # Prints concatenated string  
+
print (str + "TEST") # Prints concatenated string  
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 14:54, 3 July 2018

Why String Manipulation

All programming languages allow you to manipulate strings, it is an essential skill and function. You could use it to find a value within a string, use it to select only a part of the string and so on.

String Manipulation in Python

Print a String

str = 'Hello World!' 
print (str) # Prints complete string

Get a Character from a String

str = 'Hello World!' 
print (str[0]) # Prints first character of the string, or any character at the element provided so str[3] will get the 4th character

Get a Selection of the String from the Middle

str = 'Hello World!' 
print (str[2:5]) # Prints characters starting from 3rd to 5th, this allows you to select a part of a string

Get a Selection of the String from the Start or End

str = 'Hello World!' 
print (str[2:]) # Prints string starting from 3rd character until the end
print (str[:2]) # Prints string starting from the start and upto the 3rd character

Repeating String

str = 'Hello World!' 
print (str * 2) # Prints string two times

String Concatenation

str = 'Hello World!' 
print (str + "TEST") # Prints concatenated string