String operations

in Python 3.x

The most basic code in Python will use string variables and to do so, you need to know how to manage them. Below, all the most used python function used in Python to handle with string variable, these functions are very useful with file operation as well.

=

myvariable = "some string 123456799 &*()++++'''' \t \n"

print myvariable

some string 123456799 &*()++++''''

myvariable = ' some string 123456799 &*()++++"" \t \n'

print myvariable

some string 123456799 &*()++++"" \t \n

+

myvariable = "BLA"

myvariable += "blabla"

print myvariable

BLAblabla

same as: myvariable = myvariable + "blabla"

*: not very useful but we never know

myvariable = "BLA"

print myvariable *= 2

BLABLA

split(x): will split your string when 'x' is found. Return value is a list.

myvariable = "Hello my name is Alexandre and I'm French !\n"

myvariablesplited = myvariable.split(' ')

['Hello', 'my', 'name', 'is', 'Alexandre', 'and', 'I'm', 'French', '!\n']

replace(x, y): replace all caracters 'x' by 'y'.

myvariable = "Hello my name is Alexandre and I'm French !\n"

print myvariable.replace('Alexandre', 'Rekoc')

Hello my name is Rekoc and I'm French !

print myvariable.replace('\n', '')

Hello my name is Alexandre and I'm French !

print myvariable.replace('\n', '').replace('Alexandre', 'Rekoc')

Hello my name is Rekoc and I'm French !

if x in y: return True if 'x' is present in 'y'.

myvariable = "Hello my name is Rekoc and I'm French !\n"

if "Rekoc" in myvariable:

    print "Rekoc found !"

Rekoc found !

if x not in y: return True if 'a' doesn't exist in 'y'.

 

Wrote by Raspaud Alexandre at June 1 2018, contact alexandre.raspaud@gmail.com.