473,467 Members | 1,487 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

manipulating string question

2 New Member
I'm really new to python so I'm hoping for some serious help.

I have an application that is taking in users inputs from a text box. I need to create a python script that takes in this user sting and formats it.

The user string will look like the following examples:

999-99-999
999-99-999 or 999-99-998
999-99-999 or 999-99-998 or 999-99-997
999-99-999 or 999-99-998 or 999-99-997 or 999-99-996
and so on there could be more values separator by the or operator

So basically I would like to develop a python script that changes the value format to something like:

"APN" = '999-99-999'
"APN" = '999-99-999' or "APN" = '999-99-998'
"APN" = '999-99-999' or "APN" = '999-99-998' or "APN" = '999-99-997'
"APN" = '999-99-999' or "APN" = '999-99-998' or "APN" = '999-99-997' or "APN" = '999-99-996'
and so on

WOuld someone be kind enough to tell me how I can accomplish this.

Thanks
Jan 20 '11 #1
4 1206
bvdet
2,851 Recognized Expert Moderator Specialist
That can easily be done using string methods and formatting.
Expand|Select|Wrap|Line Numbers
  1. >>> userStr = "999-99-999 or 999-99-998 or 999-99-997"
  2. >>> strList = userStr.split(" or ")
  3. >>> output = " or ".join(["\"APN\" = \'%s\'" % (item) for item in strList])
  4. >>> print output
  5. "APN" = '999-99-999' or "APN" = '999-99-998' or "APN" = '999-99-997'
  6. >>> 
Jan 20 '11 #2
Thekid
145 New Member
I know this isn't exactly what you're looking for, but maybe you could build off of this:

Expand|Select|Wrap|Line Numbers
  1. >>>for k in range(999,989,-1):
  2.     print '"APN"=' + "'999-99-%s'" % str(k)
  3.  
  4.  
  5. "APN"='999-99-999'
  6. "APN"='999-99-998'
  7. "APN"='999-99-997'
  8. "APN"='999-99-996'
  9. "APN"='999-99-995'
  10. "APN"='999-99-994'
  11. "APN"='999-99-993'
  12. "APN"='999-99-992'
  13. "APN"='999-99-991'
  14. "APN"='999-99-990'
  15.  
Jan 20 '11 #3
Dev Player
6 New Member
I really like bvdet's solution, succinct and Pythonic. Make it in a function and you are good to go.

It's a little cryptic for some beginners as list comprehensions are not often a well practiced looping tool. All those string escapes can camoflage its elegance.

And the join() function is backwards looking to beginners too as it looks like this:
seperator.join(sequence) instead of
join(sequence, seperator)

Following I broke his recipe down into parts so you can learn to rebuild his solution. I think you could have easily figured out how to program a recipe, if you knew how to break your problem down.

As bvdet's recipe shows, the trick to your solution is to break the string apart on the seperator " or " (with spaces included there). The second trick is knowing about how to rebuild strings in Python. There are many tools to parse and build strings. Knowing these leads you to your solutions. Look at the strings library for old ways to do it. Look at str() methods for some easy ways too.

The two Python tools (s)he combines are:
1. Python format strings: "%s" % (item,)
2. and str.join() (do a dir(str) and then help(str.join))

An aside regarding your original question about user input; Look into validators. Validators are designed to work with "input". Personally I've never used them.

The not-so-Pythonic solution I give below is intended to give you some other tools that might help. Sometimes it's best to see solutions to real problems one has to see the benefits. Some tools I use below are lambda, a one line unnamed function definition, yield statement in a function to make an iterator (instead of the return statement), simpler looking list comprehensions (a fast for loop).

Also I tried to break it down and use terms which can lead you to learn templating. As user various user input might have different formats I try to show an home-grown starter "template". Templates are handy if you have lots of different formats to deal with.

The specific data you gave may be the only format you need to convert but others with a similar question my need something more adaptable.

I did this code in PySlicesShell; Google it.

Expand|Select|Wrap|Line Numbers
  1. #start code
  2. items = [
  3.     '999-99-999',
  4.     '999-99-999 or 999-99-998',
  5.     '999-99-999 or 999-99-998 or 999-99-997',
  6.     '999-99-999 or 999-99-998 or 999-99-997 or 999-99-996',
  7.     ]
  8.  
  9. seperator = ' or '
  10. prefix = '"APM" = '
  11. item_tags = "'%s'"
  12.  
  13. template = prefix + item_tags
  14. split = lambda item: item.split(seperator)
  15. tag = lambda parsed: [ template % item for item in parsed]
  16. join = lambda tagged: seperator.join( tagged )
  17. reformat = lambda item: join(tag(split(item)))
  18. process = lambda items: [reformat(item) for item in items]
  19.  
  20. def iprocess(items):
  21.     for item in items:
  22.         yield reformat(item)
  23.  
  24. #parsed = split( items[3] )
  25. #tagged = tag( parsed )
  26. #output = join( tagged )
  27. #print join(tag(split(items[3])))
  28. #print reformat(items[3])
  29.  
  30. processed = process(items)
  31. print('"""')
  32. print('Using a simple custom template-like algorithim')
  33. for item in processed: print(item)
  34.  
  35. print('\nUsing above with an iterator') 
  36. for item in iprocess(items): print(item)
  37. print('"""')
  38.  
  39. """
  40. Using a simple custom template-like algorithim
  41. "APM" = '999-99-999'
  42. "APM" = '999-99-999' or "APM" = '999-99-998'
  43. "APM" = '999-99-999' or "APM" = '999-99-998' or "APM" = '999-99-997'
  44. "APM" = '999-99-999' or "APM" = '999-99-998' or "APM" = '999-99-997' or "APM" = '999-99-996'
  45.  
  46. Using above with an iterator
  47. "APM" = '999-99-999'
  48. "APM" = '999-99-999' or "APM" = '999-99-998'
  49. "APM" = '999-99-999' or "APM" = '999-99-998' or "APM" = '999-99-997'
  50. "APM" = '999-99-999' or "APM" = '999-99-998' or "APM" = '999-99-997' or "APM" = '999-99-996'
  51. """
  52. #end code
Jan 20 '11 #4
Dev Player
6 New Member
Another wide-spread used string manipulation tool, although not really suited to your issue here is the re module, which refers to regex.

Some feel regex is clunky and learning regex is not so simple for some. But regex is used in many other programming areas outside of Python.

import re
dir(re)
help(re)
help(re.findall
)

So not for this post, but it'll help round out one's skills with string manipulation.
Jan 20 '11 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Tmenke | last post by:
Is there a way to superscript a single character in a string for example to show a number raised to a exponent ? Eg lblResult.Caption = " 52 in4 " Where the 4 would be superscripted ? ...
5
by: Veit Wiessner | last post by:
I wrote a program that handles the buildcount of projects (gets called every time I compile a project, it writes a header file which is #include-ed in the project). My question is this, is it...
51
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct...
7
by: David Schwartz | last post by:
I have a string A, and I want to write a substring (of varying lengths) starting at the beginning of A, to another string. Can someone show me how to do that?
5
by: John Baro | last post by:
I have a richtextbox which I want the "literal" rtf of. richtextbox.rtf returns {\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033\\uc1 }\r\n\0 when i put this into a string I get...
2
by: Segfahlt | last post by:
I have a fairly simple C# program that just needs to open up a fixed width file, convert each record to tab delimited and append a field to the end of it. The input files are between 300M and...
7
by: Ioannis Vranos | last post by:
I had reported this as a bug: Description: Default indexed property of System::String crashes for object with stack semantics. int main()
5
by: news.chi.sbcglobal.net | last post by:
I have a question about string literals with C++/CLI. Is there a difference between the following two lines? String ^s1 = gcnew String("Hello"); String ^s2 = gcnew String(L"Hello"); I have...
12
by: python101 | last post by:
#assume that I have a string stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS' # I would like to make it stringA = '1$ASD DSA D2$ASFSADSA FSASADSAF 3$AS' #whatever there is 'AS' it should become...
1
by: kevinridge | last post by:
Hello, I have confusing string question. I have a string like this (example): <?php $a = " {FILE: hello} hello contents {FILE: hello2} hello2 contents "; ?>
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.