Python Strings: Replace, Join, Split, Reverse, Uppercase & Lowercase
In Python everything is object and string are an object too. Python string can be created simply by enclosing characters in the double quote.
For example:
var = “Hello World!”
Accessing Values in Strings
Python does not support a character type, these are treated as strings of length one, also considered as substring.
We use square brackets for slicing along with the index or indices to obtain a substring.
var1 = "GGI123!"
var2 = "Software Testing"
print ("var1[0]:",var1[0])
print ("var2[1:5]:",var2[1:5])
Output
var1[0]: G var2[1:5]: oftw
Various String Operators
There are various string operators that can be used in different ways like concatenating different string.
Suppose if a=ggi and b=123 then a+b= “ggi123”. Similarly, if you are using a*2, it will “ggiggi”. Likewise, you can use other operators in string.
| Operator | Description | Example | Result |
|---|---|---|---|
| [] | Slice- it gives the letter from the given index | a[1] will give “g” from the word Ggi as such ( 0=g, 1=g, and 2=i ) | x=”ggi” print (x[1]) |
| [ : ] | Range slice-it gives the characters from the given range | x [1:3] it will give “ggi” from the word Guru. Remember it will not consider 0 which is G, it will consider word after that is gi. | x=”ggi” print (x[0:3]) |
| in | Membership-returns true if a letter exist in the given string | g is present in word Ggiand hence it will give 1 (True) | x=”Ggi” print (“g” in x) |
| not in | Membership-returns true if a letter exist is not in the given string | u not present in word Ggiand hence it will give 1 | x=”Ggi” print (“u” not in x) |
| r/R | Raw string suppresses actual meaning of escape characters. | Print r’\n’ prints \n and print R’/n’ prints \n | |
| % – Used for string format | %r – It insert the canonical string representation of the object (i.e., repr(o)) %s- It insert the presentation string representation of the object (i.e., str(o)) %d- it will format a number for display | The output of this code will be “ggi 123”. | name = ‘ggi’ number = 123 print (‘%s %d’ % (name,number)) |
| + | It concatenates 2 strings | It concatenate strings and gives the result | x=”Ggi” y=”123″ print (x+y) |
| * | Repeat | It prints the character twice. | x=”Ggi” y=”123″ print (x*2) |
Some more examples
You can update Python String by re-assigning a variable to another string. The new value can be related to previous value or to a completely different string all together.
x = "Hello World!" print(x[:6]) print(x[0:6] + "Ggi123")
Output
Hello Hello Ggi123
Note : – Slice:6 or 0:6 has the same effect
Python String replace() Method
The method replace() returns a copy of the string in which the values of old string have been replaced with the new value.
oldstring = 'I like Ggi'
newstring = oldstring.replace('like', 'love')
print(newstring)
Output
I love Ggi
Changing upper and lower case strings
In Python, you can even change the string to upper case or lower case.
string="python at ggi" print(string.upper())
Output
PYTHON AT GGI
Likewise, you can also do for other function as well like capitalize
string="python at ggi" print(string.capitalize())
Output
Python at ggi
You can also convert your string to lower case
string="PYTHON AT GGI" print(string.lower())
Output
python at ggi
Using “join” function for the string
The join function is a more flexible way for concatenating string. With join function, you can add any character into the string.
For example, if you want to add a colon (:) after every character in the string “Python” you can use the following code.
print(":".join("Python"))
Output
P:y:t:h:o:n
Reversing String
By using the reverse function, you can reverse the string. For example, if we have string “12345” and then if you apply the code for the reverse function as shown below.
string="12345"
print(''.join(reversed(string)))
Output
54321
Split Strings
Split strings is another function that can be applied in Python let see for string “ggi123 career ggi123”. First here we will split the string by using the command word.split and get the result.
word="ggi123 career ggi123"
print(word.split(' '))
Output
['ggi123', 'career', 'ggi123']
To understand this better we will see one more example of split, instead of space (‘ ‘) we will replace it with (‘r’) and it will split the string wherever ‘r’ is mentioned in the string
word="ggi123 career ggi123"
print(word.split('i'))
Output
['gg', '123 'career', ' gg', '123']
Important Note:
In Python, Strings are immutable.
Consider the following code
x = "Ggi"
x.replace("Ggi","Python")
print(x)
Output
Ggi
will still return Ggi. This is because x.replace(“Ggi″,”Python”) returns a copy of X with replacements made
You will need to use the following code to observe changes
x = "Ggi"
x = x.replace("Ggi","Python")
print(x)
Output
Python
Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.
Python 2 Example
#Accessing Values in Strings
var1 = "Ggi123!"
var2 = "Software Testing"
print "var1[0]:",var1[0]
print "var2[1:5]:",var2[1:5]
#Some more examples
x = "Hello World!"
print x[:6]
print x[0:6] + "Ggi123"
#Python String replace() Method
oldstring = 'I like Ggi123'
newstring = oldstring.replace('like', 'love')
print newstring
#Changing upper and lower case strings
string="python at ggi123"
print string.upper()
string="python at ggi123"
print string.capitalize()
string="PYTHON AT GGI123"
print string.lower()
#Using "join" function for the string
print":".join("Python")
#Reversing String
string="12345"
print''.join(reversed(string))
#Split Strings
word="ggi123 career ggi123"
print word.split('i')
word="ggi123 career ggi123"
print word.split('i')
x = "Ggi123"
x.replace("Ggi123","Python")
print x
x = "Ggi123"
x = x.replace("Ggi123","Python")
print x
Output
var1[0]: G var2[1:5]: oftw Hello Hello Ggi123 I love Ggi123 PYTHON AT GGI123 Python at ggi123 python at ggi123 P:y:t:h:o:n 54321 ['ggi123', 'career', 'ggi123'] ['gg', '123 ,'career', ' gg', '123'] Ggi123 Python
Python has introduced a .format function which does way with using the cumbersome %d and so on for string formatting.
» Learn more about Python String split()
Summary:
Since Python is an object-oriented programming language, many functions can be applied to Python objects. A notable feature of Python is its indenting source statements to make the code easier to read.
- Accessing values through slicing – square brackets are used for slicing along with the index or indices to obtain a substring.
- In slicing, if range is declared [1:5], it can actually fetch the value from range [1:4]
- You can update Python String by re-assigning a variable to another string
- Method replace() returns a copy of the string in which the occurrence of old is replaced with new.
- Syntax for method replace: oldstring.replace(“value to change”,”value to be replaced”)
- String operators like [], [ : ], in, Not in, etc. can be applied to concatenate the string, fetching or inserting specific characters into the string, or to check whether certain character exist in the string
- Other string operations include
- Changing upper and lower case
- Join function to glue any character into the string
- Reversing string
- Split string