Sunday, April 20, 2025

Python Replace, Split

We can replace one character with another character, in this case 'A' will be replaced with 'Z':


a = "This is A, this is B, this is group ABC"

print(a.replace("A", "Z"))

Multiple character can replace one character, too:


a = "This is A, this is B, this is group ABC"

print(a.replace("A", "RRRRRRRR"))

One word can be replaced with another word:


a = "This is A, this is B, this is group ABC"

print(a.replace("This", "555"))

How to Split String

Function split() will accept specific separator, in this case, just space:


a = "This is A, this is B, this is group ABC"

print(a.split(" "))

Result:


['This', 'is', 'A,', 'this', 'is', 'B,', 'this', 'is', 'group', 'ABC']
>>> 

In this case, we are using comma as separator:


a = "This is A, this is B, this is group ABC"

print(a.split(","))

And now, comma and space:


a = "This is A, this is B, this is group ABC"

for x in a.split(", "):
    print(x)

What you see is "for loop". In this case it is used to print all parts of string if separator is character "i":


a = "This is A, this is B, this is group ABC"

for x in a.split("i"):
    print(x)

Result: 


Th
s 
s A, th
s 
s B, th
s 
s group ABC
>>> 

In this example, we are doing split based on comma and space. After that, all results are sent to upper() function:


a = "This is A, this is B, this is group ABC"

for x in a.split(", "):
    print(x.upper())

Result: 


THIS IS A
THIS IS B
THIS IS GROUP ABC
>>> 

We will talk more about for loops.

How to get and use input from Keyboard is topic of next tutorial.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...