0
votes

I would like to use the function substr(my_var,1,2) of SAS in Python. I tried a lot of functions like contains(), split() but it didn't work.

The functions contains() and split() work only for a string value. I would like to use it on a Python Series without using a for.

Thanks a lot for your help

2

2 Answers

2
votes

A string in python can be sliced like any list:

>>> str = 'Hello World'
>>> str[1:3]
'el'
>>> str[1:-2]
'ello Wor'

To get substrings for multiple strings, you can use list comprehensions:

>>> strs = ['Hello World', 'Foobar']
>>> [ str[1:4] for str in strs]
['ell', 'oob']
1
votes

In python, you may try this:

my_var[1:3]

This gets sub string of my_var from position 1 to 3 (exclusive).